How to Create, Crop the image, Swap the cropped image, and Add 2 images using Python Code.

Chandrakant Dubey
3 min readJun 7, 2021
Source: Google(Analytic Vidhya)

For computers, a Coloured image is just a 3D array and a Black and White, Gray image is just a 2D array. Computers do not understand images, they just remember the colour codes of different colours.

How to create an Image using Python?

So to create an image using Python, we just have to create a “numpy” array(2D or 3D) whose elements are specific Colour Codes(in [B, G, R] format for 3D images) and then using “cv2” module we have to process the image.

And TaDa!!! Image created

Below is the code for creating a custom image on our own.

Note: “numpy.zeros((300,300,3))” this will create a 3D array in which all elements are Zero.

How to crop the image and swap 2 cropped images ?

These are the 2 images from which we have to crop some part from each image and then we have to swap the cropped parts of these images.

Below is the code snippet to do these 2 tasks:

  1. Cropping some part of both images, and
  2. Swapping the cropped part of images with each other.

Cropping:

For cropping the image we have to use row and column slicing.

Syntax: “cropped_img=image[a:b,c:d]”

Where a & b and c & d are the indices of the original image’s NumPy array of rows and columns respectively, in between which we have to crop the image.

Swapping:

Swapping the cropped part of images is a kind of an easy task. It is just like we swap 2 numbers in programming.

First, we have to create a temporary image and in that temporary image, we have to fit the cropped part of the first image. Then we have to fit the cropped part of the second image in the first one. At last, we have to fit the temporary image which is actually the cropped part of the first image in the second image, and our task is completed.

How to Add 2 Images using Python Code?

Adding 2 images side by side is quite an easy task. We just have to use “numpy” library’s “hstack()” method to connect 2 images.

First, let’s understand what is hstack()?

“hstack()” is a method in numpy module, that is used to connect 2 images side by side horizontally.

Similarly “vstack()” is a method in numpy module, that is used to connect 2 images vertically.

Below is the code snippet for concatenating 2 images horizontally(i.e. making a collage of 2 images).

I hope you have learned something new from this article. Do let me know in the comment section. And also comment if there is any better way you know to do these tasks, that would be appreciated.

Thank You!!!

--

--