使用Opencv python从图像裁剪凹多边形
如何从图像中裁剪凹多边形。我的输入图像看起来像 闭合的多边形的坐标为 [10,150],[150,100],[300,150],[350,100],[310,20],[35,10]. 我希望使用opencv裁剪以凹多边形为边界的区域。我搜索了其他类似的问题,但没有找到正确的答案。这就是为什么我要问这个问题?你能帮我吗使用Opencv python从图像裁剪凹多边形,python,opencv,image-processing,crop,Python,Opencv,Image Processing,Crop,如何从图像中裁剪凹多边形。我的输入图像看起来像 闭合的多边形的坐标为 [10,150],[150,100],[300,150],[350,100],[310,20],[35,10]. 我希望使用opencv裁剪以凹多边形为边界的区域。我搜索了其他类似的问题,但没有找到正确的答案。这就是为什么我要问这个问题?你能帮我吗 任何帮助都将不胜感激 您可以通过三个步骤完成: 从图像中创建一个遮罩 掩码=np.零((高度、宽度)) 点=np.数组([[[10150]、[150100]、[300150]、[
任何帮助都将不胜感激 您可以通过三个步骤完成:
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)
对于彩色背景版本,请使用如下代码:
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
im2 = np.full((res.shape[0], res.shape[1], 3), (0, 255, 0), dtype=np.uint8 ) # you can also use other colors or simply load another image of the same size
maskInv = cv2.bitwise_not(mask)
colorCrop = cv2.bitwise_or(im2,im2,mask = maskInv)
finalIm = res + colorCrop
cropped = finalIm[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]]
cv2.imshow("cropped" , cropped )
cv2.imshow("same size" , res)
cv2.waitKey(0)
台阶
# 2018.01.17 20:39:17 CST
# 2018.01.17 20:50:35 CST
import numpy as np
import cv2
img = cv2.imread("test.png")
pts = np.array([[10,150],[150,100],[300,150],[350,100],[310,20],[35,10]])
## (1) Crop the bounding rect
rect = cv2.boundingRect(pts)
x,y,w,h = rect
croped = img[y:y+h, x:x+w].copy()
## (2) make mask
pts = pts - pts.min(axis=0)
mask = np.zeros(croped.shape[:2], np.uint8)
cv2.drawContours(mask, [pts], -1, (255, 255, 255), -1, cv2.LINE_AA)
## (3) do bit-op
dst = cv2.bitwise_and(croped, croped, mask=mask)
## (4) add the white background
bg = np.ones_like(croped, np.uint8)*255
cv2.bitwise_not(bg,bg, mask=mask)
dst2 = bg+ dst
cv2.imwrite("croped.png", croped)
cv2.imwrite("mask.png", mask)
cv2.imwrite("dst.png", dst)
cv2.imwrite("dst2.png", dst2)
源图像: 结果:
你能发布原始图像吗?我试过使用你的代码,但我得到的输出是裁剪的凸面形状,而不是凹面形状。我的问题已通过@消音器答案解决。谢谢你的回答。备注-无法在评论中插入图像@希曼舒蒂瓦里我不明白。。。这应该适用于任何凸多边形或凹多边形。。。基本上两个答案都差不多,我用随机图像测试了我的代码,得到了和消音器相同的结果。。。哦,好吧,如果你设法解决了,那么一切都很好。对不起,我弄错了。但现在我得到了正确的输出。@HimanshuTiwari没问题:)有两个可能的结果可供选择总是好的:)@HimanshuTiwari即使有两个答案可供选择,也值得接受和赞许。我发现两者都很有用,可读性也很好。裁剪后如何将背景中的黑色区域更改为“白色区域”?是否可以保存没有背景的图像?我的意思是只保留那个被修剪的区域?