我有一张使用findContours
获得轮廓的图像。该产品的外观类似于以下内容:(显示“内部和外部轮廓”)。
我是否有办法获得这两个轮廓的“中点”?即某种折线正好适合图像中看到的两条线之间的距离,以使合成时间上任何点到顶部轮廓的距离与从其到底部轮廓的距离都相同?
有一种获取两个轮廓的“中点”的方法,但我认为没有现有的OpenCV解决方案。
您可以使用以下阶段:
cvtColor(... COLOR_BGR2GRAY)
和threshold(...)
OpenCV功能。floodFill
OpenCV功能。 CV_DIST_L2
作为欧氏距离。 我在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
结果: