You can draw a rotated rectangle in OpenCV Python by following the given steps. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision.
Import the OpenCV library. If OpenCV is not installed in your system then first install it using This Method.
import cv2 #cv2 is used for OpenCV library
Now read the image from the location. In my case “C:\\AiHints” is the location and “black2.jpg” is the name of the image. Change it according to your image location and name.
image = cv2.imread("C:\\AiHints\\black2.jpg") #imread is use to read an image from a location
In the following code, (320,200) is the center point of the rectangle. 320 is along the x-axis and 200 along the y_axis. In (300,150), 300 is the length and 150 is the width of the rectangle. 60 is the angle of rotation. First, try 0 degrees for understanding then change the angle according to your requirement.
rot_rectangle = ((320, 200), (300, 150), 60)
Now boxPoints will make the final four points of our desired rectangle after calculation.
box = cv2.boxPoints(rot_rectangle) box = np.int0(box) #Convert into integer values
Now we have four boundary points. Use the function cv2.drawcontours to make a rectangle on the image using the four points. The third parameter is 0 to draw only a given contour and (0,0,255) is the color combination for red. The last parameter 2 is for the thickness of the rectangle.
rectangle = cv2.drawContours(image,[box],0,(0,0,255),2)
To display the image in a specified window use ”imshow” function.
“waitKey(0)” will display a window until any key is pressed. “destroyAllWindows()” will destroy all the windows that we created.