Better Programming

Advice for programmers.

Follow publication

Member-only story

5 Useful Image Manipulation Techniques Using Python OpenCV

Yong Cui
Better Programming
Published in
8 min readOct 1, 2020

satellite image of landscape forming an abstract pattern
Photo by USGS on Unsplash

Introduction

Although many programmers don’t need to worry about processing images in their daily jobs, chances are that we may have to deal with images for small jobs. For instance, we may need to resize thousands of images to a particular size, or we may add a common background to all the images in a particular directory. Without a programmatic solution, these tasks are very tedious and time-consuming.

In this article, I want to introduce five basic image manipulation techniques using the OpenCV library that are to address some of these needs. If you haven’t installed OpenCV on your computer, you can install it very conveniently with the pip tool: pip install opencv-python. Please note that we use this library using import cv2, which is just to extend the convention of importing the old version of OpenCV with import cv.

Once you’re able to import the library without any issues, you’re good to try some functionalities in this brief tutorial. For the sake of demonstration purposes, the present article will be using the image that is shown at the beginning of the article.

Before we can manipulate images, the first thing is to read the image, which can be done conveniently with the imread function, as shown below.

  • The generated data is a numpy array. Using a numpy array allows us to manipulate the data just as manipulating the numeric values of the array.
  • The shape of the image can be accessed by its shape attribute. It tells us how large the image is, and it also tells us its composition of BGR scales (i.e., blue, green, and red). Each color constitutes a matrix of the 3D array. For instance, if we need to get the blue scale, we can use indexing original[:, :, 0].
  • The total number of pixels can be accessed by the image’s size attribute.

Yong Cui
Yong Cui

Written by Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).

No responses yet

Write a response