如何用Python循环遍历每第4个像素和每第4行?

0 投票
4 回答
3262 浏览
提问于 2025-04-15 19:59

写一个叫做listenToPicture的函数,这个函数需要一个图片作为参数。首先,它会显示这张图片。接下来,它会遍历每第四行的每第四个像素,然后进行以下操作:计算这个像素的红色、绿色和蓝色的总值,把这个总值除以9,然后再加上24。这个结果就是playNote要播放的音符编号。也就是说,像素越暗,音符就越低;像素越亮,音符就越高。它会以最大音量(127)播放这个音符,持续十分之一秒(100毫秒)。每当它移动到新的一行时,会在控制台上打印出当前行号(y值)。 你的主函数会要求用户选择一个图片文件。它会打印出要播放的音符数量(这个数量是图片中像素总数除以16;为什么要这么做呢?)。然后,它会调用listenToPicture函数。

这是我目前的进展,我不太确定如何设置每第四行的每第四个像素的循环。任何帮助都将非常感谢。

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

4 个回答

1

你可以看看这个问题。提问的人好像在做和你一样的项目。

1

这里有一些你可以用来搭建程序的基础部分:

#!/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()
3

可以考虑使用分步范围,比如 range(0, len(), 4),不过我不太清楚你的 pic 是什么类型。

撰写回答