具有透明背景的小图像的感兴趣区域

region of interest to small image with transparent background

我想从给定蒙版的图像中提取感兴趣区域 (ROI),并将其保存在一个新文件中,该文件的大小已调整为 ROI 的大小,具有透明背景。

例如给定这张图片:

我想得到这个:

这里的解决方案 NumPy/OpenCV 2: how do I crop non-rectangular region? 提供全尺寸输出图像。如何让它输出ROI的矩形大小?

我可以按位 and 图像和遮罩,但我真的不知道调整图像大小并将其保存为透明 png 的好方法。

裁剪图片可以通过

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

您首先必须计算 ROI 的矩形边界框。

给这个图片 (1.jpg) 与脚本在同一个文件夹中

以及以下蒙版图像:

我写了一个非常 hacky 的解决方案。

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()

结果: