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

mra*_*ade 3 c++ python opencv image image-processing

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

例如给定这张图片:
在此处输入图片说明
我想得到这个:
在此处输入图片说明

这里的解决方案NumPy/OpenCV 2: 如何裁剪非矩形区域?提供全尺寸的输出图像。我怎样才能让它输出 ROI 的矩形大小?

我可以按位and图像和蒙版,但我真的很困惑调整图像大小并将其另存为透明 png 的好方法。

mra*_*ade 6

给这个图像(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()
Run Code Online (Sandbox Code Playgroud)

结果:
在此处输入图片说明