opencv如何获得轮廓的中线

问题描述 投票:1回答:1

我有一张使用findContours获得轮廓的图像。该产品的外观类似于以下内容:(显示“内部和外部轮廓”)。enter image description here

我是否有办法获得这两个轮廓的“中点”?即某种折线正好适合图像中看到的两条线之间的距离,以使合成时间上任何点到顶部轮廓的距离与从其到底部轮廓的距离都相同?

c++ opencv contour
1个回答
0
投票

有一种获取两个轮廓的“中点”的方法,但我认为没有现有的OpenCV解决方案。

您可以使用以下阶段:

  • 将图像转换为灰度,然后应用二进制阈值。您可以使用cvtColor(... COLOR_BGR2GRAY)threshold(...) OpenCV功能。
  • [填充像素,使线条之间的区域超过白色。您可以使用floodFill OpenCV功能。
  • 将“距离变换”应用于二进制图像。您可以使用distanceTransform OpenCV功能。使用CV_DIST_L2作为欧氏距离。
  • 应用Dijkstra's algorithm以查找最左侧和最右侧节点之间的最短路径。将“距离变换”结果(图像)表示为加权图并应用Dijkstra算法是最具挑战性的阶段。

我在MATLAB中实现了解决方案。实现的MATLAB用作“概念证明”。我知道您期待C ++的实现,但这需要大量的工作。

MATLAB实现使用im2graph函数,我从here下载。

这是MATLAB实现:

origI = imread('two_contours.png'); % Read input image
I = rgb2gray(origI);  % Convert RGB to Grayscale.
BW = imbinarize(I); % Convert from Grayscale to binary image.

% Fill pixels outsize the area between lines.
BW2 = imfill(BW, ([1, size(I,2)/2; size(I,1), size(I,2)/2]));

% Apply "distance transform" (find compute euclidean distance from closest white pixel)
D = bwdist(BW2);

% Mark all pixels outsize the area between lines with zero.
D(BW2 == 1) = 0;

figure;imshow(D, []);impixelinfo % Display D matrix as image

[M, N] = size(D);

% Find starting point and end point - assume we need to find a path from left side to right side.
x0 = 1;
[~, y0] = max(D(:, x0));

x1 = N;
[~, y1] = max(D(:, x1));

% https://www.mathworks.com/matlabcentral/fileexchange/46088-dijkstra-lowest-cost-for-images
StartNode = y0;
EndNode = M*N - (M-y1-1);
conn = 8;%4 or 8 - connected neighborhood for linking pixels

% Use 100 - D, because graphshortestpath searches for minimum weight (and we are looking for maximum weight path).
CostMat = 100 - D;
G = im2graph(CostMat, conn);

%Find "shortest" path from StartNode to EndNode
[dist, path, pred] = graphshortestpath(G, StartNode, EndNode);

% Mark white path in image J image
J = origI;R = J(:,:,1);G = J(:,:,2);B = J(:,:,3);
R(path) = 255;G(path) = 255;B(path) = 255;
J = cat(3, R, G, B);
figure;imshow(J);impixelinfo % Display J image

结果:

D-距离转换的结果:enter image description here

[J-带有“ path”的白色原始图像:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.