In this short tutorial we will learn how to copy an image in OpenCV, using Python.
Copying an image might be useful if we need more than one instance of it. For example, we might want to manipulate the image (ex: drawing shapes on it) but still preserve the original one to display side by side. So, instead of having to read that image multiple times, we will check how to copy an image we have already loaded.
This tutorial was tested on Windows 8.1, with version 4.1.2 of OpenCV. The Python version used was 3.7.2.
As usual, we will start our code by importing the cv2 module.
Then, we will read an image from our file system. To do so, we will call the imread function from the imported cv2 module, passing as input the path to the image. For a detailed tutorial on how to read and display an image, please check here.
image = cv2.imread('C:/Users/N/Desktop/Test.jpg')
Note that the previous function call will return the image as a numpy ndarray. Thus, we will make use of the copy method of the ndarray class to obtain a copy of our image.
This method takes no arguments and returns a new ndarray that is a copy of the original one.
imageCopy = image.copy()
Now that we have a copy of our image, we will alter it a bit to show that the original one is preserved, as expected. So, we will draw a circle on it. For a detailed tutorial on how to draw circles on images with OpenCV, please check here.
In short, we simply need to call the circle function of the cv2 module, passing as first input the image, as second a tuple with the x and y coordinates of the center of the circle, as third the radius, as fourth a tuple with the color in RGB and as fifth the thickness (-1 means drawing a filled circle).
cv2.circle(imageCopy, (100, 100), 30, (255, 0, 0), -1)
To finalize, we will display both images, in different windows, and wait for the user to click a key to close the windows.
cv2.imshow('image', image) cv2.imshow('image copy', imageCopy) cv2.waitKey(0) cv2.destroyAllWindows()
The complete code can be seen below.
import cv2 image = cv2.imread('C:/Users/N/Desktop/Test.jpg') imageCopy = image.copy() cv2.circle(imageCopy, (100, 100), 30, (255, 0, 0), -1) cv2.imshow('image', image) cv2.imshow('image copy', imageCopy) cv2.waitKey(0) cv2.destroyAllWindows()
Testing the code
To test the code, simply run it in a tool of your choice. I’m using PyCharm, a Python IDE.
You should get a result similar to figure 1. As can be seen, we have both images being displayed: the original one is not changed and the second one, the copy, has the circle drawn.