[英]Python try if else loop
我正在尝试这个 try if else and except 循环。 但我不明白为什么即使检测正确,高、低或平均值为 0。
def img_text(img):
'''loads an image and recognizes text.'''
reader = easyocr.Reader(['en'])
cropped_image = img[0:280, 0:300]
result = reader.readtext(cropped_image)
for (bbox, text, prob) in result:
if prob >= 0.5:
print(f'Detected text: {text} (Probability: {prob:.2f})')
s = [letter for letter in text.split()]
print(s)
try:
if s[0] == 'H' and s[1] != None:
high = float(s[1])
else:
high = 0
except:
print("value for high temp is not detected.")
try:
if s[0] == 'L' and s[1] != None:
low =float(s[1])
else:
low = 0
except:
print("value for low temp is not detected.")
try:
if s[0] == 'A' and s[1] != None:
avg = float(s[1])
else:
avg = 0
except:
print("value for average temp is not detected.")
print(high, avg, low)
return high, avg, low
这是 function 的 output。
<class 'str'>
Detected text: C 5.1 (Probability: 0.86)
['C', '5.1']
0 0 0
<class 'str'>
Detected text: H 22.0 (Probability: 0.62)
['H', '22.0']
22.0 0 0
<class 'str'>
Detected text: L -20.7 (Probability: 0.98)
['L', '-20.7']
0 0 -20.7
<class 'str'>
Detected text: A 5.2 (Probability: 1.00)
['A', '5.2']
0 5.2 0
<class 'str'>
Detected text: P 6.6 (Probability: 1.00)
['P', '6.6']
0 0 0
这是 output,显示了高值、低值和平均值。
问题是您在任何时候不匹配时重置每个值——例如,当您看到A 3.0
时设置avg = 3.0
,但是当您看到P 4.8
时,您将其设置回0
。
要解决此问题,您应该在开始时将值归零,并且仅在有肯定匹配时才更新它们:
def img_text(img):
'''loads an image and recognizes text.'''
reader = easyocr.Reader(['en'])
cropped_image = img[0:280, 0:300]
result = reader.readtext(cropped_image)
high, avg, low = 0, 0, 0
for _, text, prob in result:
if prob < 0.5:
continue
print(f'Detected text: {text} (Probability: {prob:.2f})')
try:
label, t = text.split()
temp = float(t)
except ValueError:
continue # wrong format
if label == 'H':
high = temp
elif label == 'A':
avg = temp
elif label == 'L':
low = temp
return high, avg, low
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.