1.采集监控数据,图片识别,替换xlsx数据
from PIL import ImageGrab
import time
import pyautogui
import openpyxl
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
def find_and_click(image_path, confidence):
for attempt in range(3):
image_location = pyautogui.locateOnScreen(image_path, grayscale=True, confidence=confidence)
if image_location:
time.sleep(0.5)
position = pyautogui.center(image_location)
pyautogui.click(position)
return
else:
print(f"{image_path} 未找到指定的图片, 尝试 {attempt + 1}/3")
time.sleep(1)
print(f"{image_path} 在3次尝试后仍未找到")
def extract_text(image_path):
try:
im = Image.open(image_path)
im = im.convert('L')
im = im.point(lambda x: 0 if x < 128 else 255, '1')
text = pytesseract.image_to_string(im, lang='chi_sim')
return text
except Exception as e:
print(f"处理图片 {image_path} 时出错: {e}")
return ""
time.sleep(3)
find_and_click("./images/03.jpg", 0.8)
time.sleep(1)
pyautogui.moveTo(819,767)
time.sleep(1)
pyautogui.click()
time.sleep(4)
left, top, right, bottom = 734,415, 785,448
screenshot = ImageGrab.grab(bbox=(left, top, right, bottom))
screenshot.save('./images/01jfhjwd-wd.png')
time.sleep(1)
left, top, right, bottom = 735,453, 779,485
screenshot1 = ImageGrab.grab(bbox=(left, top, right, bottom))
screenshot1.save('./images/01jfhjwd-sd.png')
time.sleep(1)
from PIL import Image
import pytesseract
find_and_click("./images/04.jpg", 0.8)
time.sleep(1)
p1 = './images/01jfhjwd-wd.png'
p2 = './images/01jfhjwd-sd.png'
text = extract_text(p1).replace('\n', '')
text1 = extract_text(p2).replace('\n', '')
print("识别结果-空调温度:", text)
print("识别结果-空调湿度:", text1)
file_path = 'test.xlsx'
workbook = openpyxl.load_workbook(file_path)
sheet_name = '工作日志'
sheet = workbook[sheet_name]
old_text = "空调运行是否正常:正常□ 异常□,空调面板温度: ℃;湿度: Rh%。"
new_text = f"空调运行是否正常:正常□ 异常□,空调面板温度:{text}℃;湿度:{text1}Rh%。"
found = False
for row in sheet.iter_rows():
for cell in row:
if isinstance(cell.value, str) and old_text in cell.value:
cell.value = cell.value.replace(old_text, new_text)
found = True
if found:
workbook.save(file_path)
print("Excel 文件已更新。")
else:
print("未找到匹配的文本。")