OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.rotate() function is used to rotate images by multiples of 90 degrees. It is a simple and fast way to rotate an image in just one line of code. we use this image:
Example:
Pythonimport cv2
path = r'C:\Users\user\Desktop\geeks14.png'
src = cv2.imread(path)
rotated = cv2.rotate(src, cv2.ROTATE_90_CLOCKWISE)
cv2.imshow("90 Clockwise", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
[g145.png]
Explanation:
- cv2.imread() loads the image from the given file path and cv2.rotate() rotates it using a specified code like cv2.ROTATE_90_CLOCKWISE.
- cv2.imshow() displays the image in a window, cv2.waitKey(0) waits for a key press and cv2.destroyAllWindows() closes the window.
Syntax
cv2.rotate(src, rotateCode[, dst])
Parameter:
Parameter | Description |
|---|---|
src | The input image (as a NumPy array). |
rotateCode | An enum value that defines the rotation direction. |
dst(Optional) | The output image (usually ignored, since the function returns the image). |
Returns: This function returns the rotated image.
Available rotateCode values
OpenCV offers constants to rotate images by 90, 180 or 270 without manual pixel manipulation. Below are the common rotation codes and their meanings:
Constant | Description |
|---|---|
cv2.ROTATE_90_CLOCKWISE | Rotates the image 90 degrees clockwise. |
cv2.ROTATE_180 | Rotates the image 180 degrees. |
cv2.ROTATE_90_COUNTERCLOCKWISE | Rotates the image 90 degrees counterclockwise (i.e., 270 clockwise). |
Examples
Example 1: In this example, we rotate the image upside down by rotating it 180 degrees.
Pythonimport cv2
path = r'C:\Users\user\Desktop\geeks14.png'
src = cv2.imread(path)
rotated = cv2.rotate(src, cv2.ROTATE_180)
cv2.imshow("180 Rotation", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
[g217.png]
Explanation:
- cv2.imread() loads the image from the given file path and cv2.rotate() rotates it using the cv2.ROTATE_180 code, which flips the image upside down.
- cv2.imshow() displays the image in a window, cv2.waitKey(0) waits for a key press and cv2.destroyAllWindows() closes the window afterward.
Example 2: In this example, we rotate the image 270 degrees clockwise (which is equivalent to 90 degrees counterclockwise)
Pythonimport cv2
path = r'C:\Users\user\Desktop\geeks14.png'
src = cv2.imread(path)
rotated = cv2.rotate(src, cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imshow("270 Clockwise", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
[g313.png]
Explanation:
- cv2.imread() loads the image from the given file path and cv2.rotate() rotates it using the cv2.ROTATE_90_COUNTERCLOCKWISE code, which is equivalent to a 270-degree clockwise rotation (or 90 degrees to the left).
- cv2.imshow() displays the rotated image, cv2.waitKey(0) pauses for a key press and cv2.destroyAllWindows() closes the display window.