0

Im writing a function that prints a triangle. I have if loops to check the different positions of the 3 coordinates.

is there a good way to shorten this down? (The finding the position part)

the variabels should then be: x1, x2, x3, y1, y2, y3, coor1, coor2,coor3:

def filltriangel(img, coor1, coor2, coor3, color_name):

##color##
color=setcolor(color_name) 

##Tuple unpacking##
x1,y1 = coor1
x2,y2 = coor2
x3,y3 = coor3

##finding the positions of the coordinates##
if x1<=x2<x3 or x1<x2<=x3:
    if y2<y1 or y2<y3:
        for x in range(x1,x2):
            for y in range(line(coor1, coor2, x), line(coor1, coor3, x)):
                img.put(color, (x,y))
        for x in range(x2,x3):
            for y in range(line(coor2, coor3, x), line(coor1, coor3, x)):
                img.put(color, (x,y))
    if y2>y1 or y2>y3:
        for x in range(x1,x2):
            for y in range(line(coor1, coor3, x), line(coor1, coor2, x)):
                img.put(color, (x,y))
        for x in range(x2,x3):
            for y in range(line(coor1, coor3, x), line(coor2, coor3, x)):
                img.put(color, (x,y))            

if x3<=x2<x1 or x3<x2<=x1:
    if y2<y1 or y2<y3:
        for x in range(x3,x2):
            for y in range(line(coor3, coor2, x), line(coor3, coor1, x)):
                img.put(color, (x,y))
        for x in range(x2,x1):
            for y in range(line(coor2, coor1, x), line(coor3, coor1, x)):
                img.put(color, (x,y))
    if y2>y1 or y2>y3:
        for x in range(x3,x2):
            for y in range(line(coor3, coor1, x), line(coor3, coor2, x)):
                img.put(color, (x,y))
        for x in range(x2,x1):
            for y in range(line(coor3, coor1, x), line(coor2, coor1, x)):
                img.put(color, (x,y)) 

and so on......

Wysra
  • 1
  • If your code is already producing the desired result, then it sounds more like a question for [CodeReview](https://codereview.stackexchange.com/help/on-topic) – j_4321 Sep 29 '22 at 14:01

1 Answers1

0

If I understand your question, could you use a separate library to draw a line between each set of points directly on the image?

PIL or OpenCV may be able to help. Relevant code:

PIL:

draw = ImageDraw.Draw(img) 
draw.line((x1, y1, x2, y2), fill=128)

or, OpenCV:

line_thickness = 2
cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), thickness=line_thickness)
Meredith F
  • 64
  • 4