Python – Clone a NumPy array multiple times

Clone a NumPy array multiple times… here is a solution to the problem.

Clone a NumPy array multiple times

I load a picture into a numpy array and need to threshold the picture at 2 different thresholds.

import numpy as np
import cv2

cap = cv2. Videocapture(0)
_,pic = cap.read()
pic1 = pic
pic2 = pic

pic1[pic1 > 100] = 255
pic2[pic2 > 200] = 255

When I only want them to modify pic1 and pic2, this code will always edit pic

Solution

In Python, there is a difference between objects and variables. A variable is a name assigned to an object; And an object can have multiple names in memory.

Via pic1 = pic; pic2 = pic, you assign the same object to several different variable names, so you end up modifying the same object.

What you want is to create a copy using np.ndarray.copy

pic1 = pic.copy()
pic2 = pic.copy()

Or, very similarly, use np.copy

pic1, pic2 = map(np.copy, (pic, pic))

This syntax actually makes it really easy to clone pic as many times :

pic1, pic2, ... picN = map(np.copy, [pic] * N)

where N is the number of replicas you want to create.

Related Problems and Solutions