Perform the rotation

Computer vision is an exciting field that enables computers to interpret and understand digital images and video. With the power of computer vision, we can build systems that can detect objects, recognize faces, read text, and much more. Rotating images is a common task in computer vision, and the OpenCV library in Python makes it easy to do.

In this beginner‘s guide, we‘ll walk through how to use OpenCV to rotate images in Python. By the end, you‘ll be able to load an image, rotate it by any angle, and save the result. Let‘s jump in!

What is OpenCV?

OpenCV (Open Source Computer Vision) is a popular open-source library for computer vision, image processing, and machine learning. It provides a wide range of features, including object detection, face recognition, image filtering, and transformations like rotation, resizing, and cropping.

OpenCV is cross-platform, with support for Windows, macOS, Linux, Android, and iOS. It has interfaces for multiple programming languages, including Python, C++, and Java.

Using OpenCV in Python is a great choice for beginners, as Python‘s simple syntax and extensive ecosystem of scientific computing libraries make it very approachable. OpenCV‘s Python API gives us access to all of its core image processing and computer vision algorithms.

Installing OpenCV

Before we can start rotating images, we need to install OpenCV. The easiest way is using pip, Python‘s package manager. In your terminal or command prompt, run:

pip install opencv-python

This will install the latest version of OpenCV, along with numpy, a library for working with arrays that OpenCV depends on.

If you run into issues, check out OpenCV‘s official installation instructions for more details and troubleshooting tips.

Loading an Image

With OpenCV installed, we‘re ready to load an image from a file. OpenCV makes this easy with the cv2.imread() function.

First, make sure you have an image file on your computer that you want to work with. It can be any common format, like JPG, PNG, or BMP. For this example, let‘s say we have a file called "image.jpg" in the same folder as our Python script.

Here‘s the code to load the image:

import cv2

image = cv2.imread(‘image.jpg‘)

The first line imports the cv2 module, which gives us access to OpenCV‘s functions. On the second line, we use cv2.imread() to load the image from the file "image.jpg" and store it in a variable called image.

If the image file is not in the same folder as the script, you‘ll need to provide the full path, like ‘C:/Users/YourName/Pictures/image.jpg‘.

cv2.imread() returns the image as a numpy array, with each pixel represented as a list of three color values (Blue, Green, Red). If the image couldn‘t be loaded, for example if the file path was incorrect, image will be None.

Displaying the Image

Before we rotate the image, let‘s display it on the screen to make sure it loaded correctly. We can use OpenCV‘s cv2.imshow() function:

cv2.imshow(‘Original Image‘, image)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.imshow() takes two arguments: a string for the window name, and the image to display. This will open a new window titled "Original Image" with our image in it.

The cv2.waitKey(0) line tells OpenCV to wait for a key press before continuing. This keeps the image window open until we press a key. The 0 argument means it will wait indefinitely. If we used cv2.waitKey(1000) instead, it would wait for 1000 milliseconds (1 second) and then automatically close the window.

Finally, cv2.destroyAllWindows() closes any open windows. This is optional, but it‘s a good habit to clean up when we‘re done.

If you run this code, you should see your image pop up on the screen! Press any key to close it and let the script finish.

Rotating the Image

Now for the main event – rotating the image! OpenCV provides the cv2.rotate() function that makes this a breeze.

cv2.rotate() takes two arguments:

  1. The image to rotate
  2. A rotation code that specifies how to rotate it

OpenCV has three built-in rotation codes:

  • cv2.ROTATE_90_CLOCKWISE: Rotates 90 degrees clockwise
  • cv2.ROTATE_180: Rotates 180 degrees (upside down)
  • cv2.ROTATE_90_COUNTERCLOCKWISE: Rotates 90 degrees counterclockwise

Here‘s how we can use them to rotate our image:

rotated_90_clockwise = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
rotated_180 = cv2.rotate(image, cv2.ROTATE_180)  
rotated_90_counterclockwise = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)

Each line creates a new image, rotated by the specified amount. The original image is not modified.

We can display the rotated images the same way we displayed the original, using cv2.imshow():

cv2.imshow(‘Rotated 90 Clockwise‘, rotated_90_clockwise)
cv2.imshow(‘Rotated 180‘, rotated_180)  
cv2.imshow(‘Rotated 90 Counterclockwise‘, rotated_90_counterclockwise)

cv2.waitKey(0) cv2.destroyAllWindows()

This will open three new windows, each showing the image rotated by the corresponding amount. Again, press any key to close the windows when you‘re done.

Arbitrary Rotation Angles

What if you want to rotate by an angle other than 90 or 180 degrees? OpenCV has you covered with the cv2.warpAffine() function.

cv2.warpAffine() lets you apply an arbitrary affine transformation to an image. An affine transformation is a linear mapping that preserves points, straight lines, and planes. Rotation is one type of affine transformation.

To use cv2.warpAffine() for rotation, we need to provide three things:

  1. The image to rotate
  2. A 2×3 rotation matrix that specifies the angle to rotate by
  3. The size of the output image

Here‘s an example that rotates an image by 45 degrees counterclockwise:

# Calculate the rotation matrix
angle = 45
center = (image.shape[1] / 2, image.shape[0] / 2)
scale = 1.0
rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)

rotated_45 = cv2.warpAffine(image, rotation_matrix, (image.shape[1], image.shape[0]))

cv2.imshow(‘Rotated 45 Degrees‘, rotated_45) cv2.waitKey(0) cv2.destroyAllWindows()

Let‘s break this down:

  • angle is the rotation angle in degrees. Positive values mean counterclockwise rotation.
  • center is the point to rotate around, in (x, y) coordinates. Here we set it to the center of the image by dividing the width (image.shape[1]) and height (image.shape[0]) by 2.
  • scale is a scaling factor. 1.0 means no scaling, values less than 1.0 will shrink the image, values greater than 1.0 will enlarge it.
  • cv2.getRotationMatrix2D() calculates the rotation matrix based on the center point, angle, and scale.
  • cv2.warpAffine() applies the rotation matrix to the image. The third argument is the size of the output image, which we set to be the same as the input image size.

You can experiment with different angles and scaling factors to see how they affect the rotated image.

Saving the Rotated Image

After rotating the image, you may want to save the result to a new file. OpenCV‘s cv2.imwrite() function does just that.

cv2.imwrite() takes two arguments: the filename to save to, and the image to save. Here‘s how we can save our 45 degree rotated image:

cv2.imwrite(‘rotated_45.jpg‘, rotated_45)

This will create a new file called "rotated_45.jpg" in the same folder as the script, with the rotated image data.

You can use any valid filename, including a full path like ‘C:/Users/YourName/Pictures/rotated_45.jpg‘. The file extension (.jpg in this case) determines the format of the saved image. OpenCV supports saving to many common formats, including JPG, PNG, and BMP.

Tips and Tricks

Here are a few more tips to keep in mind when working with image rotation in OpenCV:

  • Rotating by 90, 180, or 270 degrees with cv2.rotate() is faster than using cv2.warpAffine() because it just rearranges the pixels without doing any interpolation. If performance is important, stick to these angles when possible.

  • When rotating by arbitrary angles with cv2.warpAffine(), you may notice black areas in the corners of the rotated image. This happens because the rotated image doesn‘t fully fit in the original image dimensions. You can fix this by calculating the size of the rotated image and using that for the output size instead of the original size.

  • If your image is very large, it may not fit on the screen when you display it with cv2.imshow(). In this case, you can resize it to a smaller size using cv2.resize() before displaying. For example, to resize to half the original size:

    resized_image = cv2.resize(image, (image.shape[1] // 2, image.shape[0] // 2))
    
  • When loading images, you can use the second argument of cv2.imread() to control how the image is read. The default is cv2.IMREAD_COLOR, which loads a color image. You can also use cv2.IMREAD_GRAYSCALE to load a grayscale image, or cv2.IMREAD_UNCHANGED to load the image as-is (including the alpha channel if present).

Next Steps

Congratulations, you now know how to rotate images using OpenCV in Python! This is a fundamental skill in computer vision that opens up many possibilities.

Some ideas to explore next:

  • Try rotating different types of images (color, grayscale, different formats) and see how OpenCV handles them
  • Experiment with other affine transformations like translation (moving the image) and scaling (resizing the image)
  • Combine rotation with other image processing techniques like thresholding, blurring, and edge detection
  • Use rotated images as input to computer vision algorithms like object detection or facial recognition

As you continue your OpenCV journey, be sure to refer to the official OpenCV documentation. It‘s a comprehensive resource with detailed explanations and examples for all of OpenCV‘s functions.

The OpenCV.org Courses page also has a great collection of tutorials and courses to help you learn more about computer vision and OpenCV.

With practice and experimentation, you‘ll be well on your way to mastering image manipulation with OpenCV. Get rotating!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts