我想绘制一条从一个明确定义的点到另一个明确定义的点的直线,然后将其转换为图像矩阵以在其上使用高斯滤波器进行平滑处理。为此,我使用函数 line
和 getframe
绘制一条线并捕获图像中的图形窗口,但是 getframe
非常慢而且不是非常可靠。我注意到当计算机被锁定时它不会捕获任何内容,并且在执行 170 次后出现内存不足
错误。
我的问题是:
- 是否有我可以使用的
getframe
的替代品? - 有没有办法创建图像矩阵并直接在其中画线?
这是一个最小的代码示例:
figure1=line([30 35] ,[200 60]);
F= getframe;
hsize=40; sigma=20;
h = fspecial('gaussian',hsize,sigma);
filteredImg = imfilter(double(F.cdata), h,256);
imshow(uint8(filteredImg));
[更新]
高性能 马克关于 linspace
的想法看起来很有前途,但我如何访问使用 linspace
计算的矩阵坐标?我尝试了以下代码,但它没有像我认为的那样工作。我认为这是一个非常简单和基本的 MATLAB 东西,但我就是无法理解它:
matrix=zeros(200,60);
diagonal=round([linspace(30,200,numSteps); linspace(35,60,numSteps)]);
matrix(diagonal(1,:), diagonal(2,:))=1;
imshow(matrix);
最佳答案
下面是一个将直线直接绘制到矩阵中的示例。首先,我们将为空图像创建一个零矩阵:
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');
关于matlab - 如何在 MATLAB 中创建一个画有线的图像矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1940833/