obelix
obelix

Reputation: 890

OpenCV - Python: How Do I split an Image in a grid?

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 ??

Upvotes: 8

Views: 10562

Answers (2)

Tbaki
Tbaki

Reputation: 1003

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 :

enter image description here

Upvotes: 1

vdudouyt
vdudouyt

Reputation: 936

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.

Upvotes: 9

Related Questions