By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,222 Members | 2,374 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,222 IT Pros & Developers. It's quick & easy.

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

P: 1
I don't know ,why it's error
This my code
Expand|Select|Wrap|Line Numbers
  1. from PIL import Image
  2.  
  3. def ch_red(tmp):
  4.  
  5.     R = tmp[0]
  6.     G = tmp[1]
  7.     B = tmp[2]
  8.  
  9.     if 60 <= R <= 99 and G <= 50 and B <= 50:
  10.         red = red + 1
  11.  
  12.     elif 100 <= R <= 139 and G <= 100 and B <= 150 :
  13.         red = red + 1
  14.  
  15.     elif 140 <= R <= 229 and G <= 160 and B <= 225 :
  16.         red = red + 1
  17.  
  18.     elif 230 <= R <= 249 and G <= 210 and B <= 210 :
  19.         red = red + 1  
  20.  
  21.     elif 250 <= R <= 255 and G <= 240 and B <= 240 :
  22.         red = red + 1  
  23.  
  24.     return red
  25.  
  26. def ck_color(s):
  27.  
  28.     for i in range(0,s.size[0]):
  29.  
  30.         for j in range(0,s.size[1]):
  31.  
  32.             tmp = s.getpixel((i,j))
  33.  
  34.             red = ch_red(tmp)
  35.  
  36.     return red
  37.  
  38. p = Image.open("c:\pypro\color\crop(150_100_270_130)\111854\111854(1).jpg")
  39.  
  40. m = ck_color(p)
  41.  
  42. print m
  43.  
when I run .It show

UnboundLocalError: 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
Jan 20 '09 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
Variable red is not defined until this statement:
Expand|Select|Wrap|Line Numbers
  1. 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
Jan 20 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.