SySu
SySu

Reputation: 619

Code is working fine, but, not working completely when the whole code is put inside a def() function

GITHUB REPO: https://github.com/sunnysinghnitb/color_detector

THE DIFFERENCE: The code inside both files is the same. But, the only difference between color_detection1.py (70 lines) and color_detection2.py (75 lines) is that the whole code inside the second file has been put in the def colo() function. Changes in lines 1, 73, 75 of color_detection2.py.

REQUIRED OUTPUT: Just run the color_detection1.py and double-click on the output image. This will show the RGB values of that particular pixel.

QUESTION: The color_detection1.py file is running fine and producing the desired output (RGB values) on double-click, while the color_detection2.py is not producing the desired output. Why is this happening? Why is color_detection2.py not working the same as color_detection1.py?

EDIT: Suppose the following is some python code (color_detection1.py) which is working fine:

.....
...
..
.....

Now, putting this code inside a function (color_detection2.py):

def colo():
    ..... 
    ...
    ..
    .....
    return
colo()

The problem is both codes are working differently. The code 1 is working as expected, while, code 2 is working partially. Why is this happening?

Upvotes: 0

Views: 84

Answers (1)

Axe319
Axe319

Reputation: 4365

Your problem is one of scope. You set globals here.

def draw_function(event, x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        global b,g,r,xpos,ypos, clicked
        clicked = True
        xpos = x
        ypos = y
        b,g,r = img[y,x]
        b = int(b)
        g = int(g)
        r = int(r)

That's all well and good but once you place the function definition inside another function you are changing the scope that you need to access it in from global to nonlocal.

Changing it to this should work.

def draw_function(event, x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        nonlocal b,g,r,xpos,ypos, clicked
        clicked = True
        xpos = x
        ypos = y
        b,g,r = img[y,x]
        b = int(b)
        g = int(g)
        r = int(r)

Your first step of debugging should be determining how far your program progresses. A little bit of logging can go a long way.

Placing a logger inside of if (clicked): would have shown you that clicked is never True even though you try to set is as such inside your function.

Placing one outside of your if statement and inside your function would show you that it is defining it in the function but not outside it.

This lets you narrow down the problem a lot more and you have a reproduceable code snippet you can post.

Upvotes: 3

Related Questions