Playing with OpenCV in Python

Arjun Chauhan
4 min readJun 5, 2021

If anyone is starting off with computer vision using python as their programming language they are most likely to use openCV2 at some point or the other.

OpenCV is pretty easy to use with straightforward implementation of the functions.

In today’s article I would be giving an idea of this library with quite unconventional examples but they are gonna give a good impression on how this library can be leveraged on different use cases.

So I would be performing three simple tasks.

  • Create a basic image using just numpy and cv2.
  • Crop image and replacing some part of it with another image
  • stacking two images together

Creating images with numpy and cv2

Before I give the example I would like to give an idea of what an image is computationally. We see image as the object it represents however for cv2 it is just a numpy array with different values of BGR colours stacked together.

So if each image is a numpy array. We can create a numpy array to be rendered as an image.

So I would be creating a simple vague lamp post.

So let’s begin now.

For our image we first need a dark background.

This creates a black background for our image.

For our light we can create a circle with the help of cv2

Here we have made a circular section of pixels as white. So it is appearing as the white spot.

Now I would be adding a frame around the light source.

Well not the best of light source but it works. Here i have added four straight segements to cover the light. The coordinates play a vital role here.

Now finally let’s add the pole.

The key takeaway here is that we have created this image by just manipulating the numpy array. CV2 was just used for viewing the array not creating it.

This trick can be used for data augmentation too or preprocessing images too.

So now let’s move on to the next part.

Cropping and swapping

Here we will be cropping part of one image and replacing it to the part of the second image.

We all know the elon and doge memes that have been circulating.

So for cropping the image I would be placing doge in elon’s image.

Cropping images just means slicing the numpy array. So here we sliced the doge’s image and changed the value of elon’s image to it. So it feels like we have cropped the image. But all we have done is sliced some part of the numpy array and replaced it.

So I guess this must be pretty clear.

Concatenating images

For the final part we will be stacking two images .

Here we will use two images of doge and cheems

For this we would be using the hstack. So the htstack takes two numpy arrays and joins them horizontally.

So here we stacked two numpy arrays horizontally.

--

--