Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone a NumPy array multiple times

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

like image 960
Hojo.Timberwolf Avatar asked Jan 29 '26 09:01

Hojo.Timberwolf


1 Answers

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.

like image 150
cs95 Avatar answered Jan 31 '26 05:01

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!