gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:18:11 29 4
gpt4 key购买 nike

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

例如给定这张图片:
enter image description here
我想得到这个:
enter image description here

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

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

最佳答案

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

以及下面的蒙版图像:
enter image description here

我写了一个非常 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()

结果:
enter image description here

关于python - 具有透明背景的小图像的感兴趣区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31153544/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com