擅长:python、mysql、java
<p>您可以通过三个步骤完成:</p>
<p>1)从图像中创建一个遮罩</p>
<pre><code>mask = np.zeros((height, width))
points = np.array([[[10,150],[150,100],[300,150],[350,100],[310,20],[35,10]]])
cv2.fillPoly(mask, points, (255))
</code></pre>
<p>2)对原始图像应用蒙版</p>
<pre><code>res = cv2.bitwise_and(img,img,mask = mask)
</code></pre>
<p>3)您可以选择将图像裁剪为更小的图像</p>
<pre><code>rect = cv2.boundingRect(points) # returns (x,y,w,h) of the rect
cropped = res[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]]
</code></pre>
<p>有了这个,你应该在最后剪掉图像</p>
<h2>更新</h2>
<p>为了完整起见,下面是完整的代码:</p>
<pre><code>import numpy as np
import cv2
img = cv2.imread("test.png")
height = img.shape[0]
width = img.shape[1]
mask = np.zeros((height, width), dtype=np.uint8)
points = np.array([[[10,150],[150,100],[300,150],[350,100],[310,20],[35,10]]])
cv2.fillPoly(mask, points, (255))
res = cv2.bitwise_and(img,img,mask = mask)
rect = cv2.boundingRect(points) # returns (x,y,w,h) of the rect
cropped = res[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]]
cv2.imshow("cropped" , cropped )
cv2.imshow("same size" , res)
cv2.waitKey(0)
</code></pre>