我想从给定掩码的图像中提取感兴趣区域(ROI),并将其保存在调整为ROI大小的新文件中,并保留透明背景。
例如给出这个图像:
我想得到这个:
此处的解决方案NumPy/OpenCV 2: how do I crop non-rectangular region?以完整大小提供输出图像。如何让它输出ROI的矩形尺寸?
我可以按位<ion-view view-title="Chats">
<ion-content>
<ion-list can-swipe="true">
<ion-item gesture-type="swipeRight" on-swipe-right="swipeRight()" class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.id}}">
<img ng-src="{{chat.face}}">
<h2>{{chat.name}}</h2>
<p>{{chat.lastText}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
<ion-option-button class="button-assertive" ng-click="share(item)" side="left">
Share
</ion-option-button>
<ion-option-button class="button-assertive" ng-click="remove(chat)" side="right">
Delete
</ion-option-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
图像和蒙版,但我真的很困惑一种调整图像大小并将其保存为透明png的好方法。
答案 0 :(得分:3)
这个图像(1.jpg)与脚本
在同一个文件夹中
以下蒙面图片:
我写了一个非常讨厌的解决方案。
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()
结果:
答案 1 :(得分:2)
可以通过
来实现裁剪图像cropped_img = masked_image[y1:y2, x1:x2]
首先必须计算投资回报率的矩形边界框。