Why? UnboundLocalError: local variable 'red' referenced before assignment

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nongnaeja
    New Member
    • Jan 2009
    • 1

    #1

    Why? UnboundLocalError: local variable 'red' referenced before assignment

    I don't know ,why it's error
    This my code
    Code:
    from PIL import Image
    
    def ch_red(tmp):
    
        R = tmp[0]
        G = tmp[1]
        B = tmp[2]
    
        if 60 <= R <= 99 and G <= 50 and B <= 50:
            red = red + 1
    
        elif 100 <= R <= 139 and G <= 100 and B <= 150 :
            red = red + 1
    
        elif 140 <= R <= 229 and G <= 160 and B <= 225 :
            red = red + 1
    
        elif 230 <= R <= 249 and G <= 210 and B <= 210 :
            red = red + 1  
    
        elif 250 <= R <= 255 and G <= 240 and B <= 240 :
            red = red + 1  
    
        return red
    
    def ck_color(s):
    
        for i in range(0,s.size[0]):
    
            for j in range(0,s.size[1]):
    
                tmp = s.getpixel((i,j))
    
                red = ch_red(tmp)
    
        return red
    
    p = Image.open("c:\pypro\color\crop(150_100_270_130)\111854\111854(1).jpg")
    
    m = ck_color(p)
    
    print m
    when I run .It show

    UnboundLocalErr or: local variable 'red' referenced before assignment

    Then I fx them to add

    'global red '

    in ch_red(tmp):
    But it show error again

    NameError: global name 'red' is not defined

    I don't know, How I fix it?
    Please.
    Thank You.
    Nae
    Last edited by bvdet; Jan 20 '09, 05:22 PM. Reason: Add code tags and indentation
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Variable red is not defined until this statement:
    Code:
    red = ch_red(tmp)
    Variable red is also local to functions ch_red() and ck_color(). The script will fail even if you declare red to be global in both functions. Can you tell us what you are trying to do?

    -BV

    Comment

    Working...