Search code examples
pythonopencvpython-imaging-library

Draw a line on an image using angle and center point using Python


I'm facing a little issue in my code. I have a dataframe of coords and angels. I want to draw a line from a certain xy coords to the edge of the image on a certain angle (say 45 degree).

How can I do that using PIL? Looping over x2 = x + length*cos(angle) doesn't look like a good solution (but I might be wrong here).

Thanks in advance.

enter image description here


Solution

  • Thanks for posting your solution. I've found a good one.

    import math
    
    def get_coords(x, y, angle, imwidth, imheight):
    
        x1_length = (x-imwidth) / math.cos(angle)
        y1_length = (y-imheight) / math.sin(angle)
        length = max(abs(x1_length), abs(y1_length))
        endx1 = x + length * math.cos(math.radians(angle))
        endy1 = y + length * math.sin(math.radians(angle))
    
        x2_length = (x-imwidth) / math.cos(angle+180)
        y2_length = (y-imheight) / math.sin(angle+180)
        length = max(abs(x2_length), abs(y2_length))
        endx2 = x + length * math.cos(math.radians(angle+180))
        endy2 = y + length * math.sin(math.radians(angle+180))
    
        return endx1, endy1, endx2, endy2
    

    Then I just draw a line between (endx1, endy1) and (endx2, endy2).

    If you have a better solution, I would be very interested to see it.