Clone a NumPy array multiple times

2020-04-11 11:39发布

问题:

I loaded a picture into a numpy array and need to threshold it 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

This code will always edit pic when I only want them to modify pic1 and pic2

回答1:

In python, there is a difference between an object and a variable. A variable is name assigned to an object; and an object can have more than one name in memory.

By doing pic1 = pic; pic2 = pic, You're assigning the same object to multiple different variable names, so you end up modifying the same object.

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

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

Or, quite similarly, using np.copy

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

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

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

Where N is the number of copies you want to create.