![](/img/trans.png)
[英]How to append column total to pandas dataframe every 4th row?
[英]How do I loop through every 4th pixel in every 4th row, using Python?
编写一个名为listenToPicture的函数,该函数将一张图片作为参数。 首先显示图片。 接下来,它将遍历每第4行中的每第4个像素并执行以下操作。 它将计算像素的红色,绿色和蓝色级别的总和,将其除以9,然后将结果加到24。该数字将是playNote播放的音符编号。 这意味着像素越暗,音符越低。 像素越轻,音符越高。 它将以最大音量(127)播放该音符达十分之一秒(100毫秒)。 每次移动到新行时,它都会在控制台上打印出行号(y值)。 您的主要功能将要求用户选择带有图片的文件。 它将打印要播放的音符数(即图片中的像素数除以16;为什么?)。 然后它将调用listenToPicture函数。
这是我到目前为止的内容,我不确定如何设置每第4行中每第4个像素的循环。 任何帮助将不胜感激。
def main():
pic= makePicture( pickAFile())
printNow (getPixels(pic)/16)
listenToPicture(pic)
def listenToPicture(pic):
show(pic)
w=getWidth(pic)
h=getHeight(pic)
for px in getPixels(pic):
r= getRed(px)
g= getGreen(px)
b= getBlue(px)
tot= (r+g+b)/9
playNote= tot + 24
分步范围可以想到range(0, len(), 4)
但我不知道您的pic
的类型。
您可以在其中建立一些基础程序:
#!/usr/bin/env python
import easygui
import Image
import numpy
filename = easygui.fileopenbox() # pick a file
im = Image.open(filename) # make picture
image_width, image_height = im.size
im.show() # show picture
ar = numpy.asarray(im) # get all pixels
N = 4
pixels = ar[::N,::4] # every 4th pixel in every N-th row
notes = pixels.sum(axis=2) / 9 + 24 # compute notes [0, 52]
print "number of notes to play:", notes.size
音符可以对应不同的音调。 我在这里使用相等的回火规模 :
# play the notes
import audiere
import time
d = audiere.open_device()
# Notes in equal tempered scale
f0, a = 440, 2**(1/12.)
tones = [d.create_tone(f0*a**n) for n in range(-26, 27)] # 53
for y, row in enumerate(notes):
print N*y # print original row number
for t in (tones[note] for note in row):
t.volume = 1.0 # maximum volume
t.play()
time.sleep(0.1) # wait around 100 milliseconds
t.stop()
您可能想看看这个问题 。 提出这个问题的人似乎与您在同一个项目上。
我想最好的方法是计算4行的偏移量,然后在行的末尾将其添加到当前位置。 因此,您进行了两次迭代:一次在行内,跳过3个像素,一次在每行末尾,跳过3行。 但是,正如msw所指出的,如果您的pic对象上没有任何信息,我们将无能为力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.