如何在Matlab中给图像画一条线?

21

假设我有两个点:

  • P(x,y) [该点位于图像顶部]
  • P'(x',y') [该点位于图像底部]

现在我想在这两个点之间画一条线...并且这条线应该出现在图像上,也就是可见的。

如何实现?


1
我相信你所问的问题之前已经有人讨论过了:https://dev59.com/5nI-5IYBdhLWcg3wQWCc,https://dev59.com/FXE95IYBdhLWcg3wE56C,http://stackoverflow.com/questions/3178336/matlab-how-to-plot-x-y-on-image-and-save,https://dev59.com/EnRB5IYBdhLWcg3wl4Sc。 - gnovice
它几乎是一个完全的副本,但并非完全相同。 - Jonas
请查看以下两个链接:http://blogs.mathworks.com/loren/2010/07/22/graphical-display-techniques-part-1/ http://blogs.mathworks.com/loren/2010/08/05/graphical-display-techniques-part-2/ - zellus
你提供的链接仅适用于二进制图像...而我的图像不是二进制的。其他链接也不适用于我的需求。因此,我需要找到其他方法。 - chee
6个回答

19
使用PLOT是在图像上画线的最简单方法。
%# read and display image
img = imread('autumn.tif');
figure,imshow(img)

%# make sure the image doesn't disappear if we plot something else
hold on

%# define points (in matrix coordinates)
p1 = [10,100];
p2 = [100,20];

%# plot the points.
%# Note that depending on the definition of the points,
%# you may have to swap x and y
plot([p1(2),p2(2)],[p1(1),p2(1)],'Color','r','LineWidth',2)

如果您想要不同的颜色,可以将字母更改为 rgbcmykw 中的任意一个,或者使用 RGB 三元组(红色为 [1 0 0])。查看线条系列属性以获取更多格式选项。

1
Chee: a)那是一个不同的问题,b)使用点斜式公式来表示一条直线。 - eric

12

从版本R2014a开始,您可以使用以下步骤使用insertShape:

img = insertShape(img,'Line',[x1 y1 x2 y2],'LineWidth',2,'Color','blue');

您还可以使用相同的命令绘制多条线,但是x1、x2、y2和y3必须是列向量,每行代表一条新线。

insertShape还允许您绘制矩形、圆形和多边形。


这只适用于您拥有计算机视觉工具箱的情况。你能建议一个不使用它的方法吗? - rayryeng
如何使用虚线? - Amarnath R

6

像这样:

figure;
hold on;
imagesc(img);
line([x1,x2],[y1,y2],'Color','r','LineWidth',2)
hold off

在图像中,y代表“下”方向,x代表“右”方向。根据需要更改颜色和宽度以使其可见。


1
如果您拥有计算机视觉工具箱,您可以简单地使用shapeInserter。
请查看http://www.mathworks.com/help/vision/ref/vision.shapeinserter-class.html 要指定线条,请使用下面的代码。否则,您可能会得到一个矩形。
示例:
%draw a line from point (100,100) to (200,200) on an image saved as nextFrame

line = int32([100 100  200 200]);
shapeInserter = vision.ShapeInserter('Shape', 'Lines');
nextFrame = step(shapeInserter, nextFrame, line);

查看属性,以了解您可以编辑什么。


1
load clown
image(X)
colormap(map)
c = size(X,2)
mid = round(c/2)
X(:,mid) = 1
image(X)

如果这是一张彩色图片,你应该使用 X(:,mid,:) = [1 1 1]; - André Caron
这是一条竖直的线。斜率为无穷大。 - MatlabDoug
在沿着线条绘制的过程中,将线条颜色设置为背景图像颜色的相反色(RGB),这样做虽然不难但更有趣。 - Y.T.

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接