ในตอนแรกที่เขียน
def ch_red(tmp):
R = tmp[0]
G = tmp[1]
B = tmp[2]
global red
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))
tt = str(i)+str(j)+str(tmp)
red = ch_red(tmp)
return white
p = Image.open("c:\pypro\color\crop(150_100_270_130)\111854\111854(1).jpg")
m = ck_color(p)
print m
รันเสร็จ เกิด
UnboundLocalError: local variable 'red' referenced before assignment
พอแก้ไข เพิ่ม
global white
ลงใน ch_white กลับมี error ว่า
NameError: global name 'red' is not defined
มันเป็นเพราะอะไรคะ ต้องแก้ที่จุดไหน ใครทราบช่วยบอกหน่อยนะคะ
ใช้ python 2.5 ค่ะ
ปวดหัว ใส่
<
code language="python">
...<
/code>
คร่อมหน่อยครับ แบบนี้ไม่ไหวครับดูที่ red = red + 1 อันแรกนะครับ ตอนนี้ red ยังไม่มีค่าอะไรเลย ยังไม่รู้ด้วยกว่าตัวเองเป็น Type ไหน (ต้องเข้าใจเรื่อง Dynamic Type ของ python ด้วยนะ)
ดูแล้วโปรแกรมนี้ไม่ต้องใช้ global ก็ได้นี่(เข้าใจความหมายของ global หรือเปล่า?)
ถ้าอยากใช้
red = red +1
ก็ควรจะให้ค่ามันก่อน
red = 0
...
red = red +1
...
แบบนี้ถึงจะได้ เพราะ red มันรู้ตัวแล้วว่ามันคือ integer ค่า 0
อ่อ เขียนย่อว่า
red += 1
ก็ได้นะครับ
ต้องประกาศตัวแปร red ก่อนครับ เพราะเราเรียกใช้ red = red + 1
แก้โดย
แต่ไม่รู้ว่าจะได้ผลลัพท์ที่ต้องการรึเปล่า
LongSpine.com
ช้าก่อน ตรงนี้อาจมีปัญหาได้
p = Image.open("c:\pypro\color\crop(150_100_270_130)\111854\111854(1).jpg")
ใน python ถ้าอยากจะใช้ \ ใน string (เพื่ออ้างอิง path ใน windows) ควรจะใส่ r นำหน้าด้วย เช่น
p = Image.open(r"c:\pypro\color\crop(150_100_270_130)\111854\111854(1).jpg")
หรือ escape มันด้วย \
<code language="python>
p = Image.open("c:\pypro\color\crop(150_100_270_130)\111854\111854(1).jpg")
def ch_red(tmp):
R = tmp[0]
G = tmp[1]
B = tmp[2]
global red
if 60 <= R <= 99 and G <= 50 and B <= 50:
elif 100 <= R <= 139 and G <= 100 and B <= 150 :
red = red + 1
elif 140 <= R <= 229 and G <= 160 and B <= 225 :
elif 230 <= R <= 249 and G <= 210 and B <= 210 :
elif 250 <= R <= 255 and G <= 240 and B <= 240 :
return red
def ck_color(s):
for i in range(0,s.size[0]):
return white
p = Image.open("c:\pypro\color\crop(150_100_270_130)\111854\111854(1).jpg")
m = ck_color(p)
print m