I am trying to split an image in a grid of smaller images so that I can process each small image separately. For that I realized that I'll have to define each small image as an ROI and I can use it easily from there.
Now, my grid size is not fixed. I.e, if user inputs 5, I have to make a grid of 5x5.
Iterating over the image pixel by pixel would be slow, so I decided to use Numpy to create ROI by using this construct :
#Assuming user entered grid size =5
roiwidth=w/5
roiheight=h/5
roi0=img[0:roiheight,0:roiwidth]
This would be my first slice. h and w are height and width of the image respectively. For the next slice I'd have to do:
roi1=img[0:roiheight,roiwidth+1:2*roiwidth]
While my last roi will be:
roi25=img[4*roiheight+1:5*roiheight, 4*roiwidth+1:5*roiwidth]
But I need to do it iteratively, and cannot figure out the correct way to do that. I don't want to iterate over the image pixel by pixel and need it to be dynamic
EDIT: I am iterating like this now:
import cv2
import numpy
img=cv2.imread('01.jpg')
h,w,chan=img.shape
rh=h/5
rw=w/5
z={}
count=0
for i in range (0,5):
for j in range (0,5):
yl=i*rh
yh=(i+1)*rh
xl=j*rw
xh=(j+1)*rw
z[count]=img[yl:yh,xl:xh]
count=count+1
But I don't know whether this is the most efficient way of doing this.
If you want to split your image using Numpy functions, take a look at numpy.array_split.
In your case you would write something like this:
z = {}
count = 0
split1 = np.array_split(img, rh)
for sub in split1:
split2 = np.array_split(sub, rw, 1)
for sub2 in split2:
z[count] = sub2
count++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With