Ivan Adanenko
Ivan Adanenko

Reputation: 585

How to split images with cv2?

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'

Upvotes: 0

Views: 1218

Answers (2)

Dara O h
Dara O h

Reputation: 149

https://pypi.org/project/empatches/

works well and it allows you to set the stride if you want to overlap patches as well as recombining patches later

from empatches import EMPatches
from cv2 import imread

original_image= imread("blah.png")

emp = EMPatches()
patchsize = 32
stride = 32

# to split
patches, indices = emp.extract_patches(
        original_image, patchsize=patchsize, stride=stride
    )

# process patches. In my case I extract a mask using unet (ML)    
new_patches = map(some_fn, patches)

# to recombine
recombined = emp.merge_patches(new_patches , indices , 'overwrite')

haven't tested the code above but this approach always works for me

Upvotes: 0

Yoskutik
Yoskutik

Reputation: 2089

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)

Upvotes: 1

Related Questions