Andrew Andrade
Andrew Andrade

Reputation: 2808

region of interest to small image with transparent background

I want to extract a region of interest (ROI) from an image given a mask, and save it in a new file resized to the size of the ROI, with a transparent background.

For example given this image:
enter image description here
I want to get this:
enter image description here

The solution here NumPy/OpenCV 2: how do I crop non-rectangular region? provides the output image at full size. How can I get it to output the rectangular size of the ROI?

I can bitwise and the image and mask, but I am really confused about a good way to resize the images and save it as a transparent png.

Upvotes: 4

Views: 3827

Answers (2)

Andrew Andrade
Andrew Andrade

Reputation: 2808

Give this this image (1.jpg) is in the same folder as the script
enter image description here

And the following masked image:
enter image description here

I wrote a really hacky solution.

import numpy as np                                                                                                                                                                                                          
import sys
import cv2        

image = cv2.imread('1.jpg')

# mask (of course replace corners with yours)
mask = np.zeros(image.shape, dtype=np.uint8)
roi_corners = np.array([[(10,10), (200,200), (10,200)]], dtype=np.int32)
white = (255, 255, 255)
cv2.fillPoly(mask, roi_corners, white)

# apply the mask
masked_image = cv2.bitwise_and(image, mask)


#shrink the top
iii = 0
#the matrix sum of back is 0
while  not np.sum(masked_image[iii,:,:]):
        resized_top = masked_image[iii+1:,:,:]
            iii = iii + 1


#shrink the bottom
size_img = resized_top.shape
iii = size_img[0]
while not np.sum(resized_top[iii-2:iii-1,:,:]):
        resized_bottom = resized_top[0:iii-1,:,:]
            iii = iii - 1

#shrink the left
iii = 0
while  not np.sum(resized_bottom[:,iii,:]):
        resized_left = resized_bottom[:,iii+1:,:]
            iii = iii + 1

#shrink the right
size_img = resized_left.shape
iii = size_img[1]
print iii
while  not np.sum(resized_left[:,iii-2:iii-1,:]):
        resized_right = resized_left[:,0:iii-1:,:]
            iii = iii - 1


#display your handywork
cv2.imshow('masked image', resized_right)
cv2.waitKey()
cv2.destroyAllWindows()

Result:
enter image description here

Upvotes: 7

Marcel Pfeiffer
Marcel Pfeiffer

Reputation: 1068

Cropping the image can be achieved through

cropped_img = masked_image[y1:y2, x1:x2]

You first have to calculate the rectangular bounding box of your ROI.

Upvotes: 0

Related Questions