How to Make a Copy of an Image in Python using the Numpy Module



Python


In this article, we show how to make a copy of an image in Python using the numpy module.

If you're going to modify an image and you want to keep the original image intact (meaning unmodified), then you have to create a copy of the original image. When you make a copy of the original image and modify this copy, it doesn't affect the original image.

So how can you create a copy of an image?

One way it can be done is through the copy() function of the numpy module.

Wtih the copy() function and passing into it the image you want to copy, a copy will be made.

This is shown in the code below.

We use the OpenCV module to read in an image. So we import cv2 for OpenCV.



So we will now go over the code.

The first thing we must do is import the modules we need in order to make and display a copy, which, in this case, are the OpenCV and numpy modules.

After this, we read in the image using the cv2.imread() function. If the image is located in the current working directory, then you simply specify the file name. If the image is not located in the current working directory, then you must specify the path to the file. This image is stored in the variable, image.

We then create another variable, imagecopy, which we set equal to, np.copy(image).

The np.copy() function allows us to create a copy of the image. This copy is now stored in the variable, imagecopy.

Now if you use the imshow() function to show the image of the copy of the original image, it should show, proving that an exact copy of the image has been made.

Now if you were to do any modifications to this copy of the image, it would not affect the original image, because it's completely separate.

And this is how to make a copy of an image in Python using the numpy module.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...