感兴趣区域转换为带透明背景的小图像

4
我想从一张给定掩码的图像中提取感兴趣的区域(ROI),并将其保存在一个新文件中,该文件的大小调整为ROI的大小,并带有透明背景。
例如,给定这张图片:
enter image description here
我想要得到这个:
enter image description here 此处的解决方案NumPy/OpenCV 2: how do I crop non-rectangular region? 提供了完整尺寸的输出图像。如何得到ROI的矩形大小的输出呢?
我可以对图像和掩码进行按位“与”操作,但是我真的很困惑如何以透明png的格式调整图像大小并保存。
2个回答

7

假设这张图片(1.jpg)与脚本在同一个文件夹中。
enter image description here

还有下面这张遮罩图片:
enter image description here

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

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

结果:
这里输入图片描述

0

可以通过裁剪图像来实现

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

首先,您需要计算您感兴趣区域的矩形边界框。


我不是在问如何裁剪一个矩形框,我是在询问如何根据掩模获取ROI的大小。 - Andrew Andrade

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接