-1

I am a beginner in image processing i am learning it using OpenCV library. While working with it i came across the following code snippet

import numpy as np  
img = np.zeros((300, 512, 3), np.uint8)    
img[:] = [b, g, r]

When i do img=[b,g,r]

It does not work as expected. I understand that this is may be because of the dimension of the array as initialized with numpy but i am not able to visualize it. Can anyone explain how this syntax work ?

Tan_R
  • 27
  • 8

2 Answers2

3

img[:] will do in-place reassignment. It'll essentially reassign img to a whole new list, but in the same place in memory.

If you do img = [b,g,r], your variable img will still point to an array [b,g,r], however, it is pointing to a completely new location now. The idea is that if you have img already, there's no need to allocate new space for [b,g,r].

M Z
  • 4,571
  • 2
  • 13
  • 27
2

Let's simplify your example a bit, and define the 3 unknowns:

In [140]: b, g, r = 1,2,3                                                       
In [141]: x = np.zeros((4,2,3),int)                                             

The img=[b,g,r] just assigns the list to the variable img. The fact that you already had assigned a value to that variable doesn't make a difference. In Python we don't "initialize" variables (as is sometimes done in other languages).

In [142]: [b,g,r]                                                               
Out[142]: [1, 2, 3]

Assigning that list to x[:] results in:

In [143]: x[:] = [b,g,r]                                                        
In [144]: x                                                                     
Out[144]: 
array([[[1, 2, 3],
        [1, 2, 3]],

       [[1, 2, 3],
        [1, 2, 3]],

       [[1, 2, 3],
        [1, 2, 3]],

       [[1, 2, 3],
        [1, 2, 3]]])

Effectively the list is converted to a (3,) array, np.array([b,g,r]). Those values are assigned, with broadcasting thus:

(3,) => (1,1,3) => (4,2,3)

And by the broadcasting rules, this would only work if b,g,r were scalars.

hpaulj
  • 221,503
  • 14
  • 230
  • 353