我使用 pytesseract 和 opencv 来识别视频中的 6 个数字变量,它们保持在恒定位置,我运行程序,选择感兴趣的窗口,但它检测到文本,我只想检测这 6 个数字在屏幕上(浮动,他们的值是 xx:xx 格式的值),我该怎么做? 感兴趣的窗口,只有 6 个数字,按以下顺序保存: 109 = v1; 00:00 = v2(可以保存为总秒数); 80 = v3 ; 1.6 = v4 ; 2.5 = v5 ; 1.1 = v6 识别后,我会将其保存在 Excel 中,记下每 2 秒更新一次的变量值。这些数字将用于定义其他代码功能,例如给出 v1 值超过限制的示例,程序会发出警告以发出噪音或执行其他操作。
我尝试使用下面的代码,但它正在检测数字(重要变量)上方的文本(不需要,但可用于保存 Excel 中的变量,例如要保存的列的名称) :
import cv2
import pandas as pd
import pytesseract
from PIL import Image
import time
# Configuração do Tesseract (certifique-se de ter o Tesseract instalado em seu sistema)
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Inicialize a planilha do Excel
excel_filename = 'dados_variaveis.xlsx'
df = pd.DataFrame(columns=['Tempo', 'Var1', 'Var2', 'Var3', 'Var4', 'Var5', 'Var6'])
# Inicialize o objeto do vídeo
video_path = 'C:\\Users\\Jayme Neto\\Desktop\\amostravideoteste.mp4'
cap = cv2.VideoCapture(video_path)
# Verifique se o vídeo foi aberto corretamente
if not cap.isOpened():
print("Erro ao abrir o vídeo.")
exit()
# Função de callback para o evento de clique do mouse
def selecionar_roi(event, x, y, flags, param):
global selecionando, x_inicial, y_inicial, x_final, y_final
if event == cv2.EVENT_LBUTTONDOWN:
selecionando = True
x_inicial, y_inicial = x, y
elif event == cv2.EVENT_LBUTTONUP:
selecionando = False
x_final, y_final = x, y
# Desenhe um retângulo na imagem para indicar a ROI
cv2.rectangle(frame, (x_inicial, y_inicial), (x_final, y_final), (0, 255, 0), 2)
cv2.imshow('Selecione a ROI', frame)
# Leia o primeiro frame para exibir a imagem
ret, frame = cap.read()
# Verifique se o frame foi lido corretamente
if not ret:
print("Erro ao ler o primeiro frame.")
exit()
# Inicialize as variáveis de seleção da ROI
selecionando = False
x_inicial, y_inicial, x_final, y_final = -1, -1, -1, -1
# Crie uma janela para exibir o vídeo e configurar o evento de clique do mouse
cv2.namedWindow('Selecione a ROI')
cv2.setMouseCallback('Selecione a ROI', selecionar_roi)
print("Clique e arraste para selecionar a região de interesse. Pressione 'ESC' quando terminar.")
while True:
cv2.imshow('Selecione a ROI', frame)
key = cv2.waitKey(1) & 0xFF
if key == 27: # Tecla 'ESC' para sair
break
# Libere os recursos da janela de seleção da ROI
cv2.destroyAllWindows()
# Continuar com a lógica original para processamento do vídeo
intervalo_captura = 2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Lógica para extrair os valores das variáveis usando Tesseract OCR
tela_variaveis = frame[y_inicial:y_final, x_inicial:x_final]
texto_extraido = pytesseract.image_to_string(Image.fromarray(tela_variaveis), config='--psm 6')
# Supondo que os valores estejam em uma linha separada por espaços
valores_variaveis = [float(valor) if ':' not in valor else time.strptime(valor, '%M:%S').tm_min + time.strptime(valor, '%M:%S').tm_sec/60
for valor in texto_extraido.split()]
# Adicione os valores à planilha
tempo_atual = time.strftime('%H:%M:%S')
df = df.append({'Tempo': tempo_atual, 'Var1': valores_variaveis[0], 'Var2': valores_variaveis[1],
'Var3': valores_variaveis[2], 'Var4': valores_variaveis[3],
'Var5': valores_variaveis[4], 'Var6': valores_variaveis[5]}, ignore_index=True)
# Salve os dados no Excel a cada intervalo
if float(time.time()) % intervalo_captura == 0:
df.to_excel(excel_filename, index=False)
# Aguarde 2 segundos (ou o intervalo desejado) antes de capturar o próximo frame
time.sleep(intervalo_captura)
# Libere os recursos
cap.release()
cv2.destroyAllWindows()
鉴于感兴趣的数字出现在恒定的屏幕位置,您可以通过屏蔽所有不相关的像素并将其设置为黑色、零来对给定的视频帧进行后期处理。