Split image into multiple grids

user6092898 picture user6092898 · Mar 21, 2018 · Viewed 7.5k times · Source

im using the following code to split the image into 20 equal parts of grid

import cv2

im =  cv2.imread("apple.jpg")
im = cv2.resize(im,(1000,500))
imgwidth=im.shape[0]
imgheight=im.shape[1]


y1 = 0
M = imgwidth//20
N = imgheight//20

for x in range(0,imgwidth,M):
    for y in range(0, imgheight, N):
        x1 = x + M
        y1 = y + N
        tiles = im[x:x+M,y:y+N]

        print(y1)
        cv2.rectangle(im, (x, y), (x1, y1), (0, 255, 0))
        cv2.imwrite("save/" + str(y)+".png",tiles)

cv2.imwrite("asas.png",im)

However i have two issues,

  1. The saved images are not of proper uniform size
  2. It only draws grid upon half of the image and not entirely.

How can I be able to sort this out?

Answer

sgarizvi picture sgarizvi · Mar 21, 2018

There is a bit of confusion which I guess is caused by how numpy handles image dimensions and coordinates using the (row, column) convention and how OpenCV handles them using (x, y) convention.

The shape member of numpy array contains image height at first index and width at second index.

A usual convention used for the naming convention is that M is the number of rows or height of the image while N is the number of columns or width of the image.

Another problem is that not all the sub-images are being saved because names are assigned using y variable only which eventually overwrites the existing images due to repetition of y. Unique names are required for saving all the sub-images. One possible way is to use both x and y to generate a unique name.

Following is a working code with all of the above-mentioned issues fixed.

import cv2

im =  cv2.imread("apple.jpg")
im = cv2.resize(im,(1000,500))

imgheight=im.shape[0]
imgwidth=im.shape[1]

y1 = 0
M = imgheight//20
N = imgwidth//20

for y in range(0,imgheight,M):
    for x in range(0, imgwidth, N):
        y1 = y + M
        x1 = x + N
        tiles = im[y:y+M,x:x+N]

        cv2.rectangle(im, (x, y), (x1, y1), (0, 255, 0))
        cv2.imwrite("save/" + str(x) + '_' + str(y)+".png",tiles)

cv2.imwrite("asas.png",im)