使用Opencv python从图像裁剪凹面多边形 [英] Cropping Concave polygon from Image using Opencv python
本文介绍了使用Opencv python从图像裁剪凹面多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从图像中裁剪出凹面多边形.我的输入图片看起来像 .
How can I crop a concave polygon from an image. My Input image look like .
和闭合多边形的坐标为 [10,150],[150,100],[300,150],[350,100],[310,20],[35,10].我希望使用opencv裁剪以凹面多边形为边界的区域.我搜索了其他类似的问题,但是找不到正确的答案.这就是为什么我要问它?你能帮我吗?
and the coordinates of closed polygon are [10,150],[150,100],[300,150],[350,100],[310,20],[35,10]. I want region bounded by concave polygon to be cropped using opencv. I searched for other similar questions but I did not able to find correct answer. That's why I am asking it ? Can you help me.
任何帮助将不胜感激.!!!
Any help would be highly appreciated.!!!
推荐答案
步骤
- 使用多点查找区域
- 使用多点创建蒙版
- 遮罩进行修剪
- 根据需要添加白色bg
- find region using the poly points
- create mask using the poly points
- do mask op to crop
- add white bg if needed
代码:
# 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)
源图像:
Source image:
结果:
这篇关于使用Opencv python从图像裁剪凹面多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文