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

Question:

I have an grayscale Image of 128×128 that I want to divide into 4×4 pixel non-overlapping blocks and I want to save coordinate of each pixel as variable like this-

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

I know I can do it manually by defining variables, but I can use any for loop for making it faster?
After that, I’ll find mean of each block by-

Average_of_block1=pixel1.mean(),pixel2.mean(),pixel3.mean(),pixel4.mean()....pixel16.mean()

Any help?Suggestions?

Asked By: Hero31

||

Answers:

To get the value of the pixel you could use PIL and
you could use a for loop and append a tuple of the x and y coordinate like this:

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

this would work for the whole image for those blocks you could just add an extra loop

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

edit:
If you want to use a grayscale image you should do this:

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

the first int in the tuple is the grayscale 0 (black) to 255 (white) the second int is the alpha but my guess would be that you don’t use alpha in a grayscale image

Answered By: Misunderstood Salad