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: I want to get this:

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.

Answers


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

And the following masked image:

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:


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.


Need Your Help

Wordpress: "Fatal error: Allowed memory size..." anytime I try to register and enqueue script in functions.php file

php wordpress

Every time I try to register and enqueue script in my function.php file I get the error

Maven and adding JARs to system scope

maven

I have a JAR in my Android project and I want it to be added to final APK.