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

cs95
  • 379,657
  • 97
  • 704
  • 746
Hojo.Timberwolf
  • 985
  • 1
  • 11
  • 32
  • Similar issue 4 hrs ago. [Code actualising automatically variables when not desired - duplicate](https://stackoverflow.com/questions/50321978/code-actualising-automatically-variables-when-not-desired). When do different variables reference the same thing, as opposed to making a copy? – hpaulj May 14 '18 at 05:55

1 Answers1

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • @liliscent To me, it's neater than `pic1 = pic.copy(); pic2 = pic.copy()`, though I suppose it's a matter of taste. – cs95 May 14 '18 at 05:57
  • I somehow find this kind of simplification will make code less readable. But anyway, it's just personal preference. – llllllllll May 14 '18 at 06:00
  • @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 – cs95 May 14 '18 at 06:00
  • 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 May 14 '18 at 06:03
  • 1
    @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. – cs95 May 14 '18 at 06:04