80

I'm new to OpenCV. What is the Python function which act the same as cv::clone() in C++?

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tintin
  • 1,459
  • 1
  • 10
  • 27

5 Answers5

127

Abid Rahman K's 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. There isn't any need to import NumPy (numpy).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ash Ketchum
  • 1,940
  • 1
  • 12
  • 6
69

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

For example:

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, the parent array.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abid Rahman K
  • 51,886
  • 31
  • 146
  • 157
14

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()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

You can simply use the 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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yildirim
  • 316
  • 7
  • 14
1

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

copy = cv2.copyMakeBorder(original,0,0,0,0,cv2.BORDER_REPLICATE)
Jack Guy
  • 8,346
  • 8
  • 55
  • 86
  • What's the benefit of the `copyMakeBorder` variant over the regular 'copy` ? Is it an attempt to avoid the notion of nparrays (which Python-OpenCV matrices are) appearing in source code? – Stéphane Gourichon Dec 19 '19 at 18:16