enter image description hereHi I want to divide an image (200x200) into 100 blocks of equal sizes and then I want to find average of each block. I have looked around a lot on how to divide the image into 10x10 blocks(10 rows 10 columns) but not able to grasp the concept on how to do so. Can anyone help.
Asked
Active
Viewed 1,462 times
1 Answers
3
I'll assume you have numpy, since you have it as a tag. If you don't have the Pillow module, run
pip install Pillow
and grab that. The following code will split the image into a 400 blocks of 10x10.
import numpy as np
from PIL import Image
image = Image.open("your_file.jpg", "r")
arr = np.asarray(image)
arr = np.split(arr, 20)
arr = np.array([np.split(x, 20, 1) for x in arr])
Then, to grab the i-j'th block, index into it via:
arr[i][j]

Daniel Nguyen
- 419
- 2
- 7
-
Is it possible to get the average of each block? – Christina Evans Oct 10 '19 at 04:54
-
arr[i][j].matrix.mean() should do the trick. @ChristinaEvans – Daniel Nguyen Oct 10 '19 at 04:58
-
it gives an error that j is not defined – Christina Evans Oct 10 '19 at 05:01
-
Try [arr[i][j].matrix.mean() for i in range(40) for j in range(40)] – Daniel Nguyen Oct 10 '19 at 05:03
-
It gives an error 'numpy.ndarray' object has no attribute 'matrix' – Christina Evans Oct 10 '19 at 05:11
-
Oops, try [arr[i][j].mean() for i in range(40) for j in range(40)] – Daniel Nguyen Oct 10 '19 at 05:19
-
Thanks a lot. You are a life savor @Daniel – Christina Evans Oct 10 '19 at 05:23
-
I have one more small question. Since we have 400 blocks shouldn't there be 400 mean values? I found the mean of each block and it shows that the length is 1600. – Christina Evans Oct 10 '19 at 05:45
-
Yeah, my original post had an error. The 40 in my previous comments should be changed to a 20 with the updated code. My apologies. – Daniel Nguyen Oct 10 '19 at 06:19