matlab - 如何在 MATLAB 中创建一个画有线的图像矩阵?

标签 matlab image-processing matrix plot line

我想绘制一条从一个明确定义的点到另一个明确定义的点的直线,然后将其转换为图像矩阵以在其上使用高斯滤波器进行平滑处理。为此,我使用函数 linegetframe 绘制一条线并捕获图像中的图形窗口,但是 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');

enter image description here

关于matlab - 如何在 MATLAB 中创建一个画有线的图像矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1940833/

相关文章:

c# - 使用 LINQ 优化图像检索

java - Android图像处理

image - 如何遍历矩阵中的一列?

python - Octave/Matlab 与 Scipy 中的周期图

c++ - 墨西哥 : error: invalid conversion from ‘void*’ to ‘double*’ [-fpermissive]

Python:如果我知道原始像素的位置,如何找到所有连接的像素?

c++ - c++测试程序中的非法系统调用(对角矩阵元素求和程序)

python - Sage 中的标量乘法?

arrays - 将向量数组相互相乘

arrays - 从向量的非零值获取相对中间索引