[英]re.findall with negative numbers, my code only works on positive numbers
我正在尝试使用 OpenCV 从屏幕上的程序中获取一个数字。 我在屏幕上有该值所在的确切位置,并且我能够使用图像到文本识别将实时更新图像转换为文本。 我得到的文本是一个字符串,如下所示(利润:12.34,无论当时是什么)我出于某种原因无法获取数字,所以我使用 re.findall 来获取字符串中的数字。 只要值是 >= 0 ,它就像一个热死的。 我得到一个作为浮点数的返回值。 工作完美。 但是第二个数字变为负数我收到此错误消息
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
到目前为止,这是我的代码
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
就像我说的,只要它不是负数,它就会每秒多次更新该数字。 有人对如何解决这个问题有任何建议吗? 或任何更好的方法来达到我的最终目标。 我搜索并发现了类似的问题,但是当我实施任何建议的解决方案时,我发现它要么完全不适用于任何数字,要么我只有数字 0 或更大的相同问题。 不知道该怎么做,请帮忙。 我包含了代码正在查看的屏幕片段 谢谢
我认为问题不在于正则表达式本身,只是它可以扩展以捕获负号。 我重新编写了您的代码以处理错误情况:
screen1 = np.array(ImageGrab.grab(bbox=(x)))
new_screen1 = process_img(screen1)
cv2.imshow('window1', new_screen1)
text = pytesseract.image_to_string(new_screen1)
if text:
# test code to show the text to scan
print("text to scan:", repr(text))
try:
price = re.findall("-?\d+", text)[0]
print(price)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
pass
except IndexError:
print("No price found")
else:
print("No text to scan")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.