crop image with grid, python

Example is to do:

Grid 5x5 and resize 200x200

Each image is numpy type.


import cv2
import numpy as np

img = cv2.imread("./data/example.jpg")

def img_to_grid(img, row, col, resize_row, resize_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]
for img in grid:
resized = cv2.resize(img, (resize_row,resize_col), interpolation = cv2.INTER_AREA)
return re_grid, len(ww), len(hh)

how_many_row, how_many_col = 5, 5
resize_row, resize_col = 200, 200
grid , r,c = img_to_grid(img, how_many_row, how_many_col, resize_row, resize_col)
print(type(grid), type(grid[0]), len(grid), r, c)


Thank you.



No comments:

Post a Comment