将图像分成 4x4 块并将每个坐标保存在变量中

Divide the image into 4x4 blocks and save each coordinate in variable

我有一个 128x128 的灰度图像,我想将其分成 4x4 像素的非重叠块,我想将每个像素的坐标保存为这样的变量-

pixel1=x,y
pixel2=x,y
pixel3=x,y
pixel4=x,y..and so on to
......
......
......
pixel16384=x,y

我知道我可以通过定义变量手动完成,但我可以使用任何 for 循环来使其更快? 之后,我会通过-

找到每个块的平均值
Average_of_block1=pixel1.mean(),pixel2.mean(),pixel3.mean(),pixel4.mean()....pixel16.mean()

任何帮助?建议?

要获取像素值,您可以使用 PIL 和 您可以使用 for 循环并附加 x 和 y 坐标的元组,如下所示:

from PIL import Image
pixels = []
i = Image.open("image.jpg")
p = i.load()
for x in range(128):
    for y in range(128):
        pixels.append(p[x,y]) #gets the RGB value

这对那些块的整个图像都有效,你可以添加一个额外的循环

from PIL import Image
pixels = []
i = Image.open("image.jpg")
p = i.load()
for b in range(4):
    block = []
    for x in range(32):
        for y in range(32):
            block.append(p[x,y])
    #do something with pixels from block

编辑: 如果你想使用灰度图像,你应该这样做:

from PIL import Image
pixels = []
i = Image.open("image.jpg").convert("LA") 
p = i.load()
for b in range(4):
    block = []
    for x in range(32):
        for y in range(32):
            block.append(p[x,y][0])
    #do something with the pixels from the block

元组中的第一个 int 是灰度 0(黑色)到 255(白色),第二个 int 是 alpha,但我猜你不会在灰度图像中使用 alpha