I would like to split an image into N*N squares, so that I can process those squares separably. How could I do the above in python using opencv ??
To do this, we use cv2. split() and cv2. merge() functions respectively.
split() method is used to split the image into individual bands. This method returns a tuple of individual image bands from an image.
In Python, you crop the image using the same method as NumPy array slicing. To slice an array, you need to specify the start and end index of the first as well as the second dimension. The first dimension is always the number of rows or the height of the image.
It's a common practice to crop a rectangle from OpenCV image by operating it as a Numpy 2-dimensional array:
img = cv2.imread('sachin.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
roi_gray = gray[y:y+h, x:x+w]
The rest is trivial and outside from OpenCV scope.
import matplotlib.pyplot as plt
import cv2
import numpy as np
%matplotlib inline
img = cv2.imread("painting.jpg")
def img_to_grid(img, row,col):
ww = [[i.min(), i.max()] for i in np.array_split(range(img.shape[0]),row)]
hh = [[i.min(), i.max()] for i in np.array_split(range(img.shape[1]),col)]
grid = [img[j:jj,i:ii,:] for j,jj in ww for i,ii in hh]
return grid, len(ww), len(hh)
def plot_grid(grid,row,col,h=5,w=5):
fig, ax = plt.subplots(nrows=row, ncols=col)
[axi.set_axis_off() for axi in ax.ravel()]
fig.set_figheight(h)
fig.set_figwidth(w)
c = 0
for row in ax:
for col in row:
col.imshow(np.flip(grid[c],axis=-1))
c+=1
plt.show()
if __name__=='__main__':
row, col =5,15
grid , r,c = img_to_grid(img,row,col)
plot_grid(grid,r,c)
Ouput :
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