How do I create an image matrix with a line drawn in it in MATLAB?

后端 未结 4 1334
眼角桃花
眼角桃花 2020-12-06 18:20

I want to plot a line from one well-defined point to another and then turn it into an image matrix to use a Gaussian filter on it for smoothing. For this I use the functions

相关标签:
4条回答
  • 2020-12-06 18:21

    Here's one example of drawing a line directly into a matrix. First, we'll create a matrix of zeros for an empty image:

    mat = zeros(250, 250, 'uint8');  % A 250-by-250 matrix of type uint8
    

    Then, let's say we want to draw a line running from (30, 35) to (200, 60). We'll first compute how many pixels long the line will have to be:

    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
    

    Next, we compute row and column indices for the line pixels using linspace, convert them from subscripted indices to linear indices using sub2ind, then use them to modify 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
    

    You can then visualize the line and the filtered version with the following:

    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');
    

    0 讨论(0)
  • 2020-12-06 18:27

    Something like this:

    [linspace(30,200,numSteps); linspace(35,60,numSteps)]

    Does that work for you ?

    Mark

    0 讨论(0)
  • 2020-12-06 18:34

    If you have Computer Vision System toolbox there is a ShapeInserter object available. This can be used to draw lines, circles, rectangles and polygons on the image.

    mat = zeros(250,250,'uint8');
    shapeInserter = vision.ShapeInserter('Shape', 'Lines', 'BorderColor', 'White');
    y = step(shapeInserter, mat, int32([30 60 180 210]));
    imshow(y);
    

    http://www.mathworks.com/help/vision/ref/vision.shapeinserterclass.html

    0 讨论(0)
  • 2020-12-06 18:46

    You can check my answer here. It is robust way to achieve what you are asking for. Advantage of my approach is that it doesn't need additional parameters to control density of the line drawn.

    0 讨论(0)
提交回复
热议问题