Matlab - 创建一个线条蒙版 [英] Matlab - create a line mask
问题描述
我有一个大小为mxn的面具。
I have a mask of size mxn.
我想在这个面具上添加一条线,这样通过它的所有点都会被设置为true。
I would like to add a line to this mask, such that all the points which passes through it will be set to true.
该行由两点定义:(x1,y1),(x2,y2)。
The line is defined by two points: (x1,y1),(x2,y2).
获得此结果的最佳方法是什么?
What is the best way to achieve this result?
请注意我只有图像处理工具箱。
Please notice that I only have the Image processing toolbox.
可能输入和所需输出的示例:
Example for possible input, and desired output:
%generates a mask
m = 152; n=131;
mask = false(m,n);
%example for possible input points
y1 = 68; x1 = 69;
y2 = 28; x2 = 75;
% code for adding the line into the mask%
imshow(mask);
期望的结果:
谢谢!
推荐答案
我们可以通过计算点之间的距离(以像素为单位)来确定两点之间有多少像素。然后我们可以使用 linspace
在两个端点之间创建指定此点数的线性间距。然后我们可以对结果进行舍入以获得像素坐标。
We can first determine how many pixels there are between the two points by computing the distance (in pixels) between the points. We can then use linspace
to create a linear spacing of points between the two end points specifying this number of points. We can then round the result to get pixel coordinates.
然后我们可以使用 sub2ind
来设置这些值。掩码到 1
。
Then we can use sub2ind
to set these values within the mask to 1
.
% Distance (in pixels) between the two endpoints
nPoints = ceil(sqrt((x2 - x1).^2 + (y2 - y1).^2)) + 1;
% Determine x and y locations along the line
xvalues = round(linspace(x1, x2, nPoints));
yvalues = round(linspace(y1, y2, nPoints));
% Replace the relevant values within the mask
mask(sub2ind(size(mask), yvalues, xvalues)) = 1;
这篇关于Matlab - 创建一个线条蒙版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!