How to split images with cv2?

Viewed 528

I have image paint.bmp. And I want to split it into 32x32 blocks. Here's my code:

import cv2

image = cv2.imread('paint.bmp')
img_h, img_w = image.shape[:2]
bl_w, bl_h = 32, 32

for i in range(int(img_h/bl_h)):
  for j in range(int(img_w/bl_w)):
    cropped = image[i*bl_h:bl_h, j*bl_w:bl_w]
    cv2.imwrite("Cropped image{}{}.bmp".format(str(i+1), str(j+1)), cropped)

The first block is saving, but after it programs crashes with:
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:715: error (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'

1 Answers

The problem is at line
cropped = image[i*bl_h:bl_h, j*bl_w:bl_w]

In the first block, you slice like this: image[0:32, 0:32], which is works fine. But, in the second block you are trying to take image[32:32, 32:32], which will always return en empty array.

There is a simplier way to do this:

import cv2

image = cv2.imread('image.bmp')
img_h, img_w = image.shape[:2]
bl_w, bl_h = 32, 32

for i in range(int(img_h/bl_h)):
  for j in range(int(img_w/bl_w)):
    cropped = image[i*bl_h:(i+1)* bl_h, j*bl_w:(j+1)*bl_w]
    cv2.imwrite("Cropped image{}{}.bmp".format(str(i+1), str(j+1)), cropped)
Related