Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Drawing a line over a black and white image

What is the best way to draw a line over a black and white (binary) image in MATLAB, provided the start and end coordinates are known?

Please note, I am not trying to add an annotation line. I would like the line to become part of the image.

like image 896
Richard Avatar asked Mar 17 '10 18:03

Richard


People also ask

How do you plot pixel intensity in Matlab?

To create an intensity profile, use the improfile function. This function calculates and plots the intensity values along a line segment or a multi line path in an image. You define the line segment (or segments) by specifying their coordinates as input arguments or interactively using a mouse.


2 Answers

You may want to look at my answer to an SO question about adding a line to an image matrix. Here's a similar example to the one I have in that answer, which will make a white line running from row and column index (10, 10) to (240, 120):

img = imread('cameraman.tif');  % Load a sample black and white image
x = [10 240];                   % x coordinates
y = [10 120];                   % y coordinates
nPoints = max(abs(diff(x)), abs(diff(y)))+1;    % Number of points in line
rIndex = round(linspace(y(1), y(2), nPoints));  % Row indices
cIndex = round(linspace(x(1), x(2), nPoints));  % Column indices
index = sub2ind(size(img), rIndex, cIndex);     % Linear indices
img(index) = 255;  % Set the line points to white
imshow(img);       % Display the image

And here's the resulting image:

enter image description here

like image 189
gnovice Avatar answered Sep 26 '22 10:09

gnovice


If you are bothered by exceptional cases of other methods here's a bullet-proof method that results in a line:

  • whose pixels always touch each other during the whole length of the line (pixels are 8-neighbors to each other),
  • density of the line is not dependent on the additional parameter, but is determined flexibly to accommodate guarantee from the first point.

Inputs (convenient for making function out of this code):

  • img - matrix that contains image,
  • x1, y1, x2, y2 - coordinates of the end points of the line to be drawn.

Code:

% distances according to both axes
xn = abs(x2-x1);
yn = abs(y2-y1);

% interpolate against axis with greater distance between points;
% this guarantees statement in the under the first point!
if (xn > yn)
    xc = x1 : sign(x2-x1) : x2;
    yc = round( interp1([x1 x2], [y1 y2], xc, 'linear') );
else
    yc = y1 : sign(y2-y1) : y2;
    xc = round( interp1([y1 y2], [x1 x2], yc, 'linear') );
end

% 2-D indexes of line are saved in (xc, yc), and
% 1-D indexes are calculated here:
ind = sub2ind( size(img), yc, xc );

% draw line on the image (change value of '255' to one that you need)
img(ind) = 255;

Here's the example image with three lines drawn on it: enter image description here

like image 32
plesiv Avatar answered Sep 25 '22 10:09

plesiv