Clone an image in cv2 python

PythonOpencv

Python Problem Overview


I'm new to opencv, here is a question, what is the python function which act the same as cv::clone() in cpp? I just try to get a rect by

    rectImg = img[10:20, 10:20]

but when I draw a line on it ,I find the line appear both on img and the rectImage,so , how can I get this done?

Python Solutions


Solution 1 - Python

The first answer is correct but you say that you are using cv2 which inherently uses numpy arrays. So, to make a complete different copy of say "myImage":

newImage = myImage.copy()

The above is enough. No need to import numpy.

Solution 2 - Python

If you use cv2, correct method is to use .copy() method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object.

eg:

In [1]: import numpy as np

In [2]: x = np.arange(10*10).reshape((10,10))

In [4]: y = x[3:7,3:7].copy()

In [6]: y[2,2] = 1000

In [8]: 1000 in x
Out[8]: False     # see, 1000 in y doesn't change values in x, parent array.

Solution 3 - Python

Using python 3 and opencv-python version 4.4.0, the following code should work:

img_src = cv2.imread('image.png')
img_clone = img_src.copy()

Solution 4 - Python

You can simply use Python standard library. Make a shallow copy of the original image as follows:

import copy

original_img = cv2.imread("foo.jpg")
clone_img = copy.copy(original_img)

Solution 5 - Python

My favorite method uses cv2.copyMakeBorder with no border, like so.

copy = cv2.copyMakeBorder(original,0,0,0,0,cv2.BORDER_REPLICATE)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontintinView Question on Stackoverflow
Solution 1 - PythonAsh KetchumView Answer on Stackoverflow
Solution 2 - PythonAbid Rahman KView Answer on Stackoverflow
Solution 3 - PythonAshadi Sedana PratamaView Answer on Stackoverflow
Solution 4 - PythonyildirimView Answer on Stackoverflow
Solution 5 - PythonJack GuyView Answer on Stackoverflow