tags:

views:

649

answers:

3

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.

+2  A: 

This algorithm offers one approach.

High Performance Mark
+3  A: 

And here is an implementation of Bresenham's line from the file exchange.

Jonas
+4  A: 

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

img = imread('cameraman.tif');  %# Load a sample black and white image
[r,c] = size(img);              %# Get the image size
rpts = linspace(10,240,1000);   %# A set of row points for the line
cpts = linspace(10,240,1000);   %# A set of column points for the line
index = sub2ind([r c],round(rpts),round(cpts));  %# Compute a linear index
img(index) = 255;               %# Set the line points to white
imshow(img);                    %# Display the image

And here's the resulting image:

alt text

gnovice
This works perfectly for a diagonal line, but may add unwanted pixels for a flatter line. If you don't care about the additional pixels, I suggest choosing gnovices solution because it is fast and simple.
Jonas
@Jonas: You're right, the above solution is more of a "quick n' dirty" algorithm. Using the Bresenham line algorithm would in general help trim a few pixels off and make the line a bit thinner and cleaner.
gnovice

related questions