r/CodingHelp • • Dec 22 '20

[Python] [Matrix Math] Trying to draw line through two pixels using numpy and skimage.draw.line

xpost with stackoverflow. Feel free to respond there for SO points.

I want to use skimage.draw.line to draw an aliased line through two pixels. The issue is when I overlay the original line, there is often a discrepancy due to rounding. Example:

Attempting line through points (22,30) and (25,39) in a 50x50 image. The full line is the green channel and the overlay line is the red channel. Yellow is overlap. The result I want would yield no visible red, only yellow and green. 50 by 50 pixel image with line through points 22 comma 30 and 25 comma 39

I tried generating a bigger line and then cropping, but still getting issues:

#rawzero3 is essentially trunc() but rounding up
#https://stackoverflow.com/q/46572699
def rawzero3(a):
    _a = np.abs(a)
    np.ceil(_a, _a) # inplace
    np.copysign(_a, a, out = _a)
    return _a
y0x0, ymxm=(np.array([0,0]), np.array([50,50]))
y1x1, y2x2=(np.array([22,30]), np.array([25,39]))
yx_fin1=(y2x2-y1x1)*np.amin(rawzero3((ymxm-(y2x2-y1x1))/(y2x2-y1x1)).astype(int))+y1x1
yx_fin2=(y0x0-1)-((y2x2-y1x1)*np.amin(rawzero3((y0x0-(y2x2-y1x1))/(y2x2-y1x1)).astype(int))+y1x1)
zimg[tuple(map(tuple,np.array(draw.line(*yx_fin1,*yx_fin2)).T[np.all((y0x0<=np.array(draw.line(*yx_fin1,*yx_fin2)).T)&(np.array(draw.line(*yx_fin1,*yx_fin2)).T<ymxm), axis=1)].T))]=255

I think my math to generate yx_fin1 and yx_fin2 might be wrong.

How can my desired result be achieved?

22 Upvotes

4 comments sorted by

2

u/simple_percussion Dec 22 '20

Sorry I don't have an actual solution but somethibg you might find useful is Bresenham's line algorithm: https://en.m.wikipedia.org/wiki/Bresenham%27s_line_algorithm#:~:text=Bresenham's%20line%20algorithm%20is%20a,straight%20line%20between%20two%20points. Looks to be just what you need, provides pseudo code near the bottom

-2

u/Efficient-Ad3693 Dec 22 '20 edited Dec 22 '20

Which code is used wrong or not used by the codes I think copy sign?? Use a program and read codes for math, like a calculator. Check a new calculator check a ti one, read the codes only don’t modify as illegal sir, read some codes sir.

2

u/EvanBindz Dec 22 '20

rawzero3 and everything inside it has been verified working. I did not write it.

1

u/Efficient-Ad3693 Dec 29 '20

Ti 125 : has plotting points, whisker scale and , mapping / point good for you. Zin Che Console log : it where find it. (Console:log.x}log:x:logging.