Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 894
obelix Avatar asked Apr 26 '14 02:04

obelix


People also ask

How do I split an image in OpenCV?

To do this, we use cv2. split() and cv2. merge() functions respectively.

How do I split an image into multiple pieces in Python?

split() method is used to split the image into individual bands. This method returns a tuple of individual image bands from an image.

How do you cut out an image in Python?

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.


2 Answers

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.

like image 101
vdudouyt Avatar answered Nov 14 '22 23:11

vdudouyt


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

like image 27
Tbaki Avatar answered Nov 14 '22 23:11

Tbaki