3

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@liliscent To me, it's neater than pic1 = pic.copy(); pic2 = pic.copy(), though I suppose it's a matter of taste.
I somehow find this kind of simplification will make code less readable. But anyway, it's just personal preference.
@liliscent Sure, I can respect that. I picked this up from Andras Deak, and found I quite liked the succinctness of it... of course it isn't for the faint of heart :p
Does the map function increase or decrease processing time? I hope to be processing a stream with the code. (I'm trying to determine the presence of 2 objects)
@Hojo.Timberwolf The difference is "seriously, don't worry about it" small, but you can look at the alt just below it if you're not interested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.