MATLAB: Drawing a line over a black and white image

Richard picture Richard · Mar 17, 2010 · Viewed 18.3k times · Source

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.

Answer

gnovice picture gnovice · Mar 17, 2010

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