问题描述
在这里的第一篇文章,我一直在寻找解决问题的解决方案,但没有结果,我向您寻求帮助。 我对 Python 有足够的经验,但对 OpenCV 的经验很少:我正在尝试分析并获得一条切割线来修剪材料,排除轮廓附近的缺陷。
在材料图像上,我已经能够获得外轮廓和内轮廓(用于切割),不包括边缘附近的缺陷。
然而,内部轮廓尽管在识别缺陷方面很完美, 即使是不应该切割的部分也总是会留下偏移。
我附上照片以使其清楚:红色外边缘(有缺陷),黄色内边缘以消除缺陷:
在这张照片中有一个我想要获得的轮廓示例(抱歉,用油漆完成了):
我在这里和互联网上尝试了几次搜索来寻找想法,我研究了不同的方法(opencv、numpy、scipy、shapely),但无论如何我都没有得到想要的结果。
在实践中,我的难点是识别(我认为应该是一个解决方案)两个轮廓之间的平行度(但是,它们非常分割),然后当它们之间的距离变远时,使黄色轮廓与外部红色轮廓重合两者小于 X 值。
谢谢。
解决方法
这样做有点笨拙,但是您可以比较从内部轮廓上的点到外部轮廓上的点的距离,如果距离小于某个阈值,则可以“紧贴”到外部轮廓。
你的图像在星星的边缘有一些奇怪的伪影,所以我在 Paint 中绘制了自己的图像。
原始图片
在“紧贴”之后(25 距离截止)
import cv2
import numpy as np
import math
# 2d distance
def dist2D(p1,p2):
dx = p1[0] - p2[0];
dy = p1[1] - p2[1];
return math.sqrt(dx*dx + dy*dy);
# cling to closest point
def cling(point,other_points,cutoff):
# find closest point
best_dist = 10000000; # JUST A BIG NUMBER
best_point = [0,0];
for op in other_points:
dist = dist2D(point,op);
if dist < best_dist:
best_dist = dist;
best_point = op[:];
# if less than cutoff,cling to point
if best_dist <= cutoff:
return best_point;
return point;
# go through each point on inner and cling to nearby outer points
def clingy(inner,outer,cutoff):
new_inner = [];
for point in inner:
point = cling(point,cutoff);
new_inner.append(point);
return new_inner;
# load image
img = cv2.imread("my_stars.png");
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY);
# make a mask
mask_outer = cv2.inRange(gray,1);
mask_inner = cv2.inRange(gray,2,254);
# contours OpenCV3.4,if you're using OpenCV 2 or 4,it returns (contours,_)
_,_ = cv2.findContours(mask_outer,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE);
_,inner,_ = cv2.findContours(mask_inner,cv2.CHAIN_APPROX_NONE);
# just take the first contour
outer = outer[0];
inner = inner[0];
# strip out annoying extra brackets
stripped_inner = np.array([p[0] for p in inner]);
stripped_outer = np.array([p[0] for p in outer]);
# cling
cling_inner = clingy(stripped_inner,stripped_outer,25);
# add back in annoying brackets
cling_inner = np.array([[p] for p in cling_inner]);
# draw on original image
cv2.drawContours(img,[cling_inner],-1,(240,200,0),-1);
# draw original contour again
cv2.drawContours(img,[inner],(150,100,1);
# show
cv2.imshow("Image",img);
cv2.waitKey(0);