下载地址:https://www.pan38.com/share.php?code=pvvmX 提取码:8888 【仅供学习用途】
OCR实时检测订单列表并自动右滑的完整代码方案,包含多个模块,包含OCR处理、价格分析、滑动控制和主逻辑四个模块,实现了实时监控订单列表、识别价格并自动右滑的功能。代码使用了多线程处理确保实时性,并通过队列管理任务。
import cv2
import numpy as np
import pytesseract
from PIL import Image
class OCRProcessor:
def init(self):
pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract'
self.price_pattern = r'\$\d+.\d{2}'
def preprocess_image(self, img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
return opening
def extract_text(self, img):
processed = self.preprocess_image(img)
text = pytesseract.image_to_string(processed, config='--psm 6')
return text
re
from typing import List, Tuple
class PriceAnalyzer:
def init(self, target_price: float):
self.target_price = target_price
self.price_regex = re.compile(r'(\$|£|€)?(\d+.\d{2})')
def find_prices(self, text: str) -> List[Tuple[float, int]]:
matches = self.price_regex.finditer(text)
results = []
for match in matches:
try:
price = float(match.group(2))
results.append((price, match.start()))
except ValueError:
continue
return results
def check_price_match(self, prices: List[Tuple[float, int]]) -> bool:
for price, _ in prices:
if abs(price - self.target_price) < 0.01:
return True
return False
threading import Thread
import queue
class OrderMonitor:
def init(self, device_id, target_price):
self.ocr = OCRProcessor()
self.analyzer = PriceAnalyzer(target_price)
self.controller = SwipeController(device_id)
self.task_queue = queue.Queue()
self.running = False
def process_frame(self):
while self.running:
try:
img = self.controller.capture_screen()
text = self.ocr.extract_text(img)
prices = self.analyzer.find_prices(text)
if self.analyzer.check_price_match(prices):
y_pos = self.calculate_swipe_position(prices, img.shape[0])
self.controller.swipe_right(y_pos)
time.sleep(1)
except Exception as e:
print(f"Error: {e}")
def calculate_swipe_position(self, prices, img_height):
# 根据价格位置计算滑动Y坐标
_, text_y = prices[0][1] # 获取第一个价格的位置
return text_y / img_height
def start(self):
self.running = True
worker = Thread(target=self.process_frame)
worker.daemon = True
worker.start()
def stop(self):
self.running = False
if name == "main":
monitor = OrderMonitor("emulator-5554", 19.99)
monitor.start()
input("Press Enter to stop...")
monitor.stop()