'Python try if else loop
I am trying this try if else and except loop. But I can't understand why high, low or avg values are 0 even if it is detected correctly.
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
Here is the output of the function.
<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
Here is the output showing the values of high, low and avg.
Solution 1:[1]
The problem is that you're resetting each value any time it's not a match -- you set avg = 3.0 when you see A 3.0, for example, but then when you see P 4.8 you set it back to 0.
To fix this, you should zero the values at the beginning, and only update them when you have a positive match:
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
