2024-05-17 02:35:11 发布
网友
如何从图像中裁剪凹多边形。我的输入图像看起来像 。
闭合多边形的坐标是 [10150],[150100],[300150],[350100],[310,20],[35,10]。我想用opencv裁剪以凹多边形为边界的区域。我搜索了其他类似的问题,但没有找到正确的答案。所以我才问这个?你能帮助我吗。
任何帮助都将不胜感激。!!!
Stepsfind region using the poly pointscreate mask using the poly pointsdo mask op to cropadd white bg if needed
Steps
代码:
# 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)
源图像:
结果:
您可以通过三个步骤完成:
1)从图像中创建一个遮罩
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))
2)对原始图像应用蒙版
res = cv2.bitwise_and(img,img,mask = mask)
3)您可以选择将图像裁剪为更小的图像
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]]
有了这个,你应该在最后剪掉图像
为了完整起见,下面是完整的代码:
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)
代码:
源图像:
结果:
您可以通过三个步骤完成:
1)从图像中创建一个遮罩
2)对原始图像应用蒙版
3)您可以选择将图像裁剪为更小的图像
有了这个,你应该在最后剪掉图像
更新
为了完整起见,下面是完整的代码:
相关问题 更多 >
编程相关推荐