File Exchange

## Connect two pixels

version 1.0 (2.6 KB) by

Draw a line between two pixels with any grayscale in any image.

3.69231
13 Ratings

Updated

Connect two pixels in an image with the desired graylevel

Command line
------------
result = func_DrawLine(Img, X1, Y1, X2, Y2)
input: Img : the original image.
(X1, Y1), (X2, Y2) : points to connect.
nG : the gray level of the line.
output: result

Note
----
Img can be anything
(X1, Y1), (X2, Y2) should be NOT be OUT of the Img

The computation cost of this program is around half as Cubas's [1]
[1] As for Cubas's code, please refer

Example
-------
result = func_DrawLine(zeros(5, 10), 2, 1, 5, 10, 1)
result =
0 0 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0 0
0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1

Thijs Bruins Slot

### Thijs Bruins Slot (view profile)

Why so complex? This worked fine for me in 3D:

function img = Drawline3D(img, X0, Y0, Z0, X1, Y1, Z1)

for n = 0:(1/round(sqrt((X1-X0)^2 + (Y1-Y0)^2 + (Z1-Z0)^2))):1
xn = round(X0 +(X1 - X0)*n);
yn = round(Y0 +(Y1 - Y0)*n);
zn = round(Z0 +(Z1 - Z0)*n);
img(xn,yn,zn) = 1;
end

end

Putra A

Omar

### Omar (view profile)

Thanks for sharing.
I would suggest adding a line thickness option.

Jamie Schirf

Thanks for sharing. This was just what I needed for a task.

Graham Cranston

input coordinates X and Y are implemented inverted. That is, the coordinates given as X0 and X1 are used as the starting and ending ROW in the matrix, and vice versa. A simple find replace fixed the problem.

Rajesh Govind

I agree there exists jaggedness while it traces the line, but otherwise, I like the implementation :) Good work appreciated .. this saved my time as well ! Thanks a ton !

cano lee

interesting, but could u disclose more technical details?

Ed Zwaan

It doesn't draw a line straight between the pixels, it has some offset.

Saeed Mozaffari

It works well

kevino z

yeah, it seems that the line is always one pixel to the right and above the start/end points

Yuan luo

good

Afshan naz

chim wicket

very good, it save much time for me.

user anonymous

Does n't work really well - the lines are broken and sometimes it doesn't connect the two pixels at all!!

HY WANG

MATLAB 6.5 (R13)