2013-03-11 547 views
21

我有一組點,使形狀(閉合多段線)。現在我想從這個形狀內部複製/裁剪一些圖像中的所有像素,其餘部分保持黑色/透明。我該怎麼做呢?NumPy/OpenCV 2:如何裁剪非矩形區域?

例如,我有這樣的:

enter image description here

,我想這一點:

enter image description here

+0

我相信你會想要使用不規則的ROI(感興趣的區域)。你可能從這裏開始:http://stackoverflow.com/questions/10632195/define-image-roi-with-opencv-in-c – 2013-03-11 15:24:01

+0

以防萬一:這個問題不重複,因爲引用的人描述C API而不是Python (雖然這個問題仍然有幫助)。 – ffriend 2013-03-11 21:23:39

回答

34

*編輯 - 更新與alpha通道圖像的工作。

這爲我工作:

  • 做一個面具與全黑(全屏蔽)
  • 用白色填充的多邊形在您的投資回報率
  • 結合面膜的形狀和你的形象得到與其他地方的黑色投資回報率

您可能只是想保留圖像和掩碼分開的功能,接受蒙版。不過,我相信這是你所特別要求的:

import cv2 
import numpy as np 

# original image 
# -1 loads as-is so if it will be 3 or 4 channel as the original 
image = cv2.imread('image.png', -1) 
# mask defaulting to black for 3-channel and transparent for 4-channel 
# (of course replace corners with yours) 
mask = np.zeros(image.shape, dtype=np.uint8) 
roi_corners = np.array([[(10,10), (300,300), (10,300)]], dtype=np.int32) 
# fill the ROI so it doesn't get wiped out when the mask is applied 
channel_count = image.shape[2] # i.e. 3 or 4 depending on your image 
ignore_mask_color = (255,)*channel_count 
cv2.fillPoly(mask, roi_corners, ignore_mask_color) 
# from Masterfool: use cv2.fillConvexPoly if you know it's convex 

# apply the mask 
masked_image = cv2.bitwise_and(image, mask) 

# save the result 
cv2.imwrite('image_masked.png', masked_image) 
+0

完美!謝謝! – ffriend 2013-03-11 21:19:49

+0

@kobejohn創建面具使這個作物的透明背景? – kju 2015-12-07 04:36:34

+0

@ kju你的意思是你想在投資回報率之外透明而不是黑色? – KobeJohn 2015-12-07 13:54:15