2015-07-01 37 views
2

我想從給定蒙版的圖像中提取感興趣區域(ROI),並將其保存在調整爲ROI大小的新文件中,並使用透明背景。感興趣的區域與透明背景的小圖像

例如,給定這一形象:
enter image description here
我想要得到這樣的:
enter image description here

該解決方案在這裏NumPy/OpenCV 2: how do I crop non-rectangular region?全尺寸提供了輸出圖像。我怎樣才能得到它的投資回報率矩形大小?

我可以逐位and的圖像和麪具,但我真的很困惑調整圖像的大小和保存爲一個透明PNG的好方法。

回答

2

給這個這個圖像(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() 

結果:
enter image description here

2

裁剪圖像可以通過

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

實現你首先要計算投資回報率的矩形邊框。

+0

我不問如何裁剪一個長方形的盒子,我詢問如何獲得投資回報率的大小給予面罩 – mrandrewandrade