Search code examples
pythonopencvmathgraphicsdrawing

Rotate a Multiple Lines in OpenCV/Python


I have many lines in my opencv, I want to rotate them but Opencv does not have shape rotation functionality. It has image rotation function.

I made a rectangle and drew the lines on it. then I rotated it with cv2.getRotationMatrix2D. I tried creating a mask with cv2.addWeighted and adding the lines on the image, but it didn't work properly.

I drew some examples using Canva:

enter image description here

enter image description here

enter image description here

This is the code I use to draw the lines:

def draw_lines(img, color, cx, cy, deg):

    deg = int(deg)

    for a in range(720, -720, -30):

        img = cv2.line(img, (cx-165, cy+a),  (cx+165, cy+a), color, 1,cv2.LINE_AA)
            
    return img

How can i rotate these lines using only math?

*info: Bended Lines Example(Not Rotate): I want to rotate them.

Bended Lines


Solution

  • A rotation matrix rotates vectors around the origin (0, 0). You always have to consider in which coordinate system the vectors are that you want to rotate.

    Putting your code and the example together:

    import numpy as np
    import cv2
    from math import cos, sin
    
    
    def draw_lines(img, color, cx, cy, deg):
        theta = np.deg2rad(deg)
        rot = np.array([[cos(theta), -sin(theta)], [sin(theta), cos(theta)]])
    
        c = np.array([cx, cy])
    
        for a in range(720, -720, -30):
            v1 = np.dot(rot, np.array([-165, a])).astype(int)
            v2 = np.dot(rot, np.array([165, a])).astype(int)
    
            img = cv2.line(img, c + v1, c + v2, color, 1, cv2.LINE_AA)
    
        return img
    
    
    def main():
        img = np.zeros((2000, 2000, 3), np.uint8)  # create empty black image
        draw_lines(img, [255, 255, 255], 1000, 1000, 30)
        cv2.imwrite("out.png", img)
    
    
    main()