MATLAB:在黑白图像上画一条线

Ric*_*ard 14 matlab image image-processing line matlab-cvst

如果已知起点和终点坐标,在MATLAB中在黑白(二进制)图像上绘制线条的最佳方法是什么?

请注意,我不是要添加注释行.我希望这条线成为图像的一部分.

gno*_*ice 9

你可能想看看对一个关于在图像矩阵中添加一条线的问题的答案.这是我在该答案中的一个类似示例,它将使行和列索引的白线运行(10, 10)(240, 120):

img = imread('cameraman.tif');  % Load a sample black and white image
x = [10 240];                   % x coordinates
y = [10 120];                   % y coordinates
nPoints = max(abs(diff(x)), abs(diff(y)))+1;    % Number of points in line
rIndex = round(linspace(y(1), y(2), nPoints));  % Row indices
cIndex = round(linspace(x(1), x(2), nPoints));  % Column indices
index = sub2ind(size(img), rIndex, cIndex);     % Linear indices
img(index) = 255;  % Set the line points to white
imshow(img);       % Display the image
Run Code Online (Sandbox Code Playgroud)

这是最终的图像:

在此输入图像描述

  • 这适用于对角线,但可能会为更平坦的线条添加不需要的像素.如果你不关心额外的像素,我建议选择gnovices解决方案,因为它快速而简单. (5认同)

ple*_*siv 5

如果您对其他方法的特殊情况感到困扰,这里的防弹方法会产生一条线:

  • 在整个行长期间,像素总是相互接触(像素彼此相邻8个像素),
  • 线的密度不依赖于附加参数,而是灵活地确定以适应来自第一点的保证.

输入(方便用这个代码制作功能):

  • img - 包含图像的矩阵,
  • x1,y1,x2,y2-线的终点坐标绘制.

码:

% distances according to both axes
xn = abs(x2-x1);
yn = abs(y2-y1);

% interpolate against axis with greater distance between points;
% this guarantees statement in the under the first point!
if (xn > yn)
    xc = x1 : sign(x2-x1) : x2;
    yc = round( interp1([x1 x2], [y1 y2], xc, 'linear') );
else
    yc = y1 : sign(y2-y1) : y2;
    xc = round( interp1([y1 y2], [x1 x2], yc, 'linear') );
end

% 2-D indexes of line are saved in (xc, yc), and
% 1-D indexes are calculated here:
ind = sub2ind( size(img), yc, xc );

% draw line on the image (change value of '255' to one that you need)
img(ind) = 255;
Run Code Online (Sandbox Code Playgroud)

这是在其上绘制三条线的示例图像: 在此输入图像描述


Hig*_*ark 3

该算法提供了一种方法。