I am trying to get a number from a program on my screen using OpenCV. I have the exact spot on the screen that the value is at and I am able to use image to text recognition to turn the live updating image into text. the text I get is a string as follows (profit: 12.34, whatever it is at the time) I am for some reason unable to just get the number so I am using re.findall to get the number in the string. it works like a hot damn as long as the value is >= 0 . I get a returned value as a float. works perfect. but the second the number goes negative I get this error message
File "C:/Users/austi/.spyder-py3/OpenCV_Files/Closest_workingCV.py", line 55, in <module>
price = re.findall("\d+", text)[0]
IndexError: list index out of range
here is my code thus far
import numpy as np
from PIL import ImageGrab
import cv2
import time
import pytesseract
import re
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
while True:
def process_img(original_image):
processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
return processed_img
def process_img1(original_image1):
processed_img1 = cv2.cvtColor(original_image1, cv2.COLOR_BGR2GRAY)
processed_img1 = cv2.Canny(processed_img1, threshold1=200, threshold2=300)
return processed_img1
coor1 = (20, 150, 950, 950)
coor2 = (60, 550, 250, 590)
# coor3 = (20, 150, 950, 950)
#last_time = time.time()
for i in range(2):
if i == 0:
x = coor1
screen = np.array(ImageGrab.grab(bbox=(x)))
new_screen = process_img(screen)
#screen('Loop took {} seconds'.format(time.time()-last_time))
#last_time = time.time()
cv2.imshow('window', new_screen)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
elif i == 1:
x = coor2
screen1 = np.array(ImageGrab.grab(bbox=(x)))
new_screen1 = process_img(screen1)
cv2.imshow('window1', new_screen1)
text = pytesseract.image_to_string(new_screen1)
#price = text.split(":")[1]
price = re.findall("\d+", text)[0]
#rint(repr(text))
#price = re.findall("\d+","Foo -111 Bar 55", text)
price = float(price)
#text = [float(s) for s in re.findall(r'-?\d+\.?\d*', text)]
#print(text)
print(price)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
like I said it updates that number multiple times a second flawlessly so long as its not a negative number.
anyone have any suggestions on how to fix this? or any better ways to get to my end goal.
I've searched and found similar issues but when I implement any proposed solutions that I have found it either flat out does not work for any number or I have the same issue of only numbers 0 or greater. not sure what to do please help. i included the snippet of my screen that the code is looking at
Thanks