# 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.

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

I wrote a really hacky solution.

```import numpy as np
import sys
import cv2

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

#shrink the top
iii = 0
#the matrix sum of back is 0
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

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.