以下是将线直接绘制到矩阵中的一个示例.首先,我们将为空的图像创建一个零的矩阵:
mat = zeros(250, 250, 'uint8'); % A 250-by-250 matrix of type uint8
然后,假设我们要画一条从(30,35)到(200,60)的线.我们首先计算该行将要有多少个像素长度:
x = [30 200]; % x coordinates (running along matrix columns)
y = [35 60]; % y coordinates (running along matrix rows)
nPoints = max(abs(diff(x)), abs(diff(y)))+1; % Number of points in line
接下来,我们使用linspace计算行像素的行和列索引,使用sub2ind将它们从下标索引转换为线性索引,然后使用它们来修改mat:
rIndex = round(linspace(y(1), y(2), nPoints)); % Row indices
cIndex = round(linspace(x(1), x(2), nPoints)); % Column indices
index = sub2ind(size(mat), rIndex, cIndex); % Linear indices
mat(index) = 255; % Set the line pixels to the max value of 255 for uint8 types
然后,您可以使用以下内容来可视化该行和过滤版本:
subplot(1, 2, 1);
image(mat); % Show original line image
colormap(gray); % Change colormap
title('Line');
subplot(1, 2, 2);
h = fspecial('gaussian', 20, 10); % Create filter
filteredImg = imfilter(mat, h); % Filter image
image(filteredImg); % Show filtered line image
title('Filtered line');