如何提取适合粗线轮廓中间的线方程

时间:2017-03-18 04:50:07

标签: python matlab opencv geometry computer-vision

我检测到了一个线轮廓,我想用一个线方程来描述它。

我尝试了最小的方形拟合,但是由于透视失真,线的一端较粗,因此线方程在一端漂移到一侧。

我也考虑过使用zhang-suen细化方法,但这样的算法似乎过度杀死了一条简单的行

enter image description here enter image description here

1 个答案:

答案 0 :(得分:3)

一种简单有效的方法是计算线上第一个 principal component 点。这是matlab中的代码:

% Read image
im = imread('https://i.stack.imgur.com/pJ5Si.png');

% Binarize image and extract indices of line pixels
imbw = imbinarize(rgb2gray(im), 'global');  % Threshold with Otsu's method
[y, x] = ind2sub(size(imbw), find(imbw));   % Get indices of line pixels

% Extract first principal component
C = cov(x, y);                              % Compute covariance of x and y
coeff = pcacov(C);                          % Compute eigenvectors of C
vector_xy = [coeff(1,1), coeff(2,1)];       % Get fist principal component

% Plot
figure; imshow(im); hold on
xx = vector_xy(1) * [-1 1] * size(imbw,2) + mean(x(:));
yy = vector_xy(2) * [-1 1] * size(imbw,2) + mean(y(:));
plot(xx,yy,'c','LineWidth',2)
axis on, legend('Principal Axis','Location','NorthWest')

enter image description here

您可以使用

获取线方程y = a*x + b的系数
a = vector_xy(2) / vector_xy(1);
b = mean(y(:)) - a * mean(x(:));