【问题标题】:OpenCv - Contours segments unionOpenCv - 轮廓线段联合
【发布时间】:2021-07-26 05:30:48
【问题描述】:

第一次在这里发帖,我一直在寻找解决问题的方法几天没有结果,我请你帮忙。 我对 Python 有足够的经验,但对 OpenCV 的经验很少:我正在尝试分析并获得一条切割线来修剪材料,不包括轮廓附近的缺陷。

在材料图像上,我已经能够获得外轮廓和内轮廓(用于切割),不包括边缘附近的缺陷。

然而,内部轮廓,尽管在识别缺陷方面非常完美, 即使与不应该切割的部分也总是留下偏移

我附上照片说明:红色外缘(有缺陷),黄色内缘消除缺陷:

outer and inner contours

在这张照片中,有一个我想要获得的轮廓示例(对不起,用油漆完成):

inner contour aspected

我在这里和互联网上尝试了几次搜索以寻找想法,并且我研究了不同的方法(opencv、numpy、scipy、shapely),但无论如何我都无法获得想要的结果。

在实践中,我的困难是识别(我认为应该是一个解决方案)两个轮廓之间的平行度(但是,它们非常分段),然后当两者之间的距离时使黄色轮廓与外部红色轮廓重合两者都小于 X 值。

您对解决问题的方法有什么想法吗?

谢谢。

【问题讨论】:

标签: python opencv opencv-contour opencv-drawcontour


【解决方案1】:

这样做有点笨拙,但是您可以比较内轮廓上的点与外轮廓上的点的距离,如果距离小于某个阈值,则“紧贴”外轮廓。

你的图像在星星的边缘有一些奇怪的伪影,所以我在 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, outer, 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, 0, 1);
mask_inner = cv2.inRange(gray, 2, 254);

# contours OpenCV3.4, if you're using OpenCV 2 or 4, it returns (contours, _)
_, outer, _ = cv2.findContours(mask_outer, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE);
_, inner, _ = cv2.findContours(mask_inner, cv2.RETR_TREE, 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], -1, (150,100,0), 1);

# show
cv2.imshow("Image", img);
cv2.waitKey(0);

【讨论】:

  • 非常感谢!我正在测试你的代码,我终于开始得到接近我想要达到的结果。唯一的问题是,对于大图像 (3000x3000),计算速度非常慢。
  • 您可以尝试 cv2.CHAIN_APPROX_SIMPLE 的 findContours 函数来减少它返回的点数。您可以使用 approxPolyDp 进一步减少它。但是,减少点数可能会降低附着函数的准确性,因此您必须先尝试一下,看看可以减少多少,以免您不喜欢它的外观。
猜你喜欢
  • 2020-07-04
  • 1970-01-01
  • 2023-03-18
  • 2011-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多