![](/img/trans.png)
[英]Measuring distances between pixels of an irregular bounded object in an Image with Python and OpenCV
[英]opencv sharply bounded extracted image
首先我们找到平滑的轮廓,然后使用approxPolyDP
其拉直为四边形:
import cv2
import numpy as np
img = cv2.imread(r'c:\TEMP\so57564249.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold and shrink mask
_, thresh = cv2.threshold(img_gray, 10, 255, cv2.THRESH_BINARY)
thresh = cv2.erode(thresh, np.ones((10,10), np.uint8), iterations=1)
# find countour
contours,_ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
# straighten contour to quadrilateral
epsilon = 0.001*cv2.arcLength(cnt,True)
while True:
epsilon += epsilon
approx = cv2.approxPolyDP(cnt,epsilon,True)
if len(approx) <= 4:
break
# output
thresh[:,:] = 0
thresh = cv2.fillPoly(thresh, [approx], 255)
img = cv2.bitwise_and(img, img, mask=thresh)
cv2.polylines(img, [approx], True, (0,255,0), 2)
选择内核大小10来消除图像的模糊边缘几乎是任意的。 您可能需要调整它。 要显示其效果,您可以添加
cv2.polylines(img, [cnt], True, (0,0,255))
在最后一行之后绘制初始贴图图像的平滑轮廓。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.