Jelajahi Sumber

修复图片识别路径

yichael 5 bulan lalu
induk
melakukan
bb2ce7f875

+ 10 - 2
main-js/history.js

@@ -70,12 +70,20 @@ export async function matchImageAndGetCoordinate(ipPort, templateImagePath) {
     // 使用虚拟环境中的 Python 解释器
     const pythonExePath = join(__dirname, '..', 'py', 'venv', 'Scripts', 'python.exe');
     const pythonScriptPath = join(__dirname, '..', 'py', 'img-reg.py');
-    const command = `"${pythonExePath}" "${pythonScriptPath}" "${screenshotPath}" "${absoluteTemplatePath}" ${width} ${height}`;
+    
+    // 确保路径使用正斜杠,避免 Windows 路径问题
+    const normalizedScreenshotPath = screenshotPath.replace(/\\/g, '/');
+    const normalizedTemplatePath = absoluteTemplatePath.replace(/\\/g, '/');
+    
+    // 使用 -u 参数确保输出不被缓冲,并设置 UTF-8 编码
+    const command = `"${pythonExePath}" -u "${pythonScriptPath}" "${normalizedScreenshotPath}" "${normalizedTemplatePath}" ${width} ${height}`;
     
     const { stdout, stderr } = await execAsync(command, {
       timeout: 10000,
       maxBuffer: 10 * 1024 * 1024,
-      cwd: join(__dirname, '..')
+      cwd: join(__dirname, '..'),
+      encoding: 'utf8',
+      env: { ...process.env, PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' }
     });
 
     // 5. 解析 Python 脚本输出

TEMPAT SAMPAH
py/__pycache__/img-reg.cpython-312.pyc


+ 59 - 18
py/img-reg.py

@@ -7,6 +7,33 @@ import cv2
 import numpy as np
 from pathlib import Path
 from typing import Tuple, Optional
+import os
+
+
+def read_image_with_unicode_path(image_path):
+    """
+    读取包含 Unicode 字符(如中文)的图片路径
+    OpenCV 的 imread 在 Windows 上可能无法直接处理中文路径
+    直接使用 imdecode 方法,避免 imread 的警告
+    """
+    # 将路径转换为绝对路径并规范化
+    abs_path = os.path.abspath(str(image_path))
+    
+    # 直接使用文件读取 + imdecode,避免 imread 在中文路径上的问题
+    # 这样可以避免 cv2.imread 输出的警告信息
+    try:
+        with open(abs_path, 'rb') as f:
+            image_data = f.read()
+        # 将字节流解码为图片
+        img_array = np.frombuffer(image_data, np.uint8)
+        img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
+        if img is None:
+            raise ValueError(f"cv2.imdecode 无法解码图片: {abs_path}")
+        return img
+    except FileNotFoundError:
+        raise FileNotFoundError(f"图片文件不存在: {abs_path}")
+    except Exception as e:
+        raise ValueError(f"无法读取图片: {abs_path}, 错误: {e}")
 
 
 def match_image(
@@ -35,14 +62,9 @@ def match_image(
     if not img2_path.exists():
         raise FileNotFoundError(f"图片2不存在: {image2_path}")
     
-    # 读取图片
-    img1 = cv2.imread(str(img1_path))
-    img2 = cv2.imread(str(img2_path))
-    
-    if img1 is None:
-        raise ValueError(f"无法读取图片1: {image1_path}")
-    if img2 is None:
-        raise ValueError(f"无法读取图片2: {image2_path}")
+    # 读取图片(使用支持中文路径的方法)
+    img1 = read_image_with_unicode_path(img1_path)
+    img2 = read_image_with_unicode_path(img2_path)
     
     # 如果提供了图片1的尺寸,则缩放图片1
     if image1_size is not None:
@@ -109,14 +131,9 @@ def match_image_multiple(
     if not img2_path.exists():
         raise FileNotFoundError(f"图片2不存在: {image2_path}")
     
-    # 读取图片
-    img1 = cv2.imread(str(img1_path))
-    img2 = cv2.imread(str(img2_path))
-    
-    if img1 is None:
-        raise ValueError(f"无法读取图片1: {image1_path}")
-    if img2 is None:
-        raise ValueError(f"无法读取图片2: {image2_path}")
+    # 读取图片(使用支持中文路径的方法)
+    img1 = read_image_with_unicode_path(img1_path)
+    img2 = read_image_with_unicode_path(img2_path)
     
     # 如果提供了图片1的尺寸,则缩放图片1
     if image1_size is not None:
@@ -170,14 +187,32 @@ def match_image_multiple(
 if __name__ == "__main__":
     # 测试示例
     import sys
+    import os
+    
+    # 设置 UTF-8 编码,确保能正确处理中文路径
+    if sys.platform == 'win32':
+        import codecs
+        sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
+        sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
     
     if len(sys.argv) < 3:
         print("用法: python img-reg.py <图片1路径> <图片2路径> [图片1宽度] [图片1高度]")
         print("示例: python img-reg.py screenshot.png template.png 1920 1080")
         sys.exit(1)
     
-    img1_path = sys.argv[1]
-    img2_path = sys.argv[2]
+    # 处理路径:将正斜杠转换回反斜杠(Windows),并确保路径正确
+    img1_path = sys.argv[1].replace('/', os.sep)
+    img2_path = sys.argv[2].replace('/', os.sep)
+    
+    # 确保路径是绝对路径,并规范化路径
+    if not os.path.isabs(img1_path):
+        img1_path = os.path.abspath(img1_path)
+    if not os.path.isabs(img2_path):
+        img2_path = os.path.abspath(img2_path)
+    
+    # 规范化路径(移除多余的斜杠等)
+    img1_path = os.path.normpath(img1_path)
+    img2_path = os.path.normpath(img2_path)
     
     image1_size = None
     if len(sys.argv) >= 5:
@@ -188,6 +223,12 @@ if __name__ == "__main__":
         except ValueError:
             print("警告: 无法解析图片1尺寸,将使用原始尺寸")
     
+    # 验证文件是否存在
+    if not os.path.exists(img1_path):
+        raise FileNotFoundError(f"图片1不存在: {img1_path}")
+    if not os.path.exists(img2_path):
+        raise FileNotFoundError(f"图片2不存在: {img2_path}")
+    
     try:
         result = match_image(img1_path, img2_path, image1_size)
         if result:

+ 23 - 0
src/pages/ScreenShot/ScreenShot.css

@@ -9,6 +9,21 @@
   box-sizing: border-box;
   overflow: hidden;
   background-color: #0a0a0a;
+  position: relative;
+}
+
+.ScreenShot-container.no-padding {
+  padding: 0;
+  align-items: stretch;
+  justify-content: flex-start;
+  position: absolute;
+  top: 0;
+  left: 0;
+  right: 0;
+  bottom: 0;
+  width: 100%;
+  height: 100%;
+  margin: 0;
 }
 
 .screenshot-frame {
@@ -31,6 +46,14 @@
 .screenshot-frame.filled {
   border: none;
   background: transparent;
+  width: 100%;
+  height: 100%;
+  max-width: 100%;
+  max-height: 100%;
+  aspect-ratio: 1280 / 2400;
+  margin: 0;
+  align-self: stretch;
+  flex-shrink: 0;
 }
 
 .screenshot-img {

+ 1 - 1
src/pages/ScreenShot/ScreenShot.jsx

@@ -13,7 +13,7 @@ function ScreenShot() {
   useInputEvents(currentDevice, !!currentDevice);
 
   return (
-    <div className="ScreenShot-container">
+    <div className={`ScreenShot-container ${currentDevice ? 'no-padding' : ''}`}>
       {!currentDevice && (
         <div className="screenshot-frame">
           <div className="screenshot-placeholder">等待预览...</div>

+ 1 - 0
src/pages/home.css

@@ -19,4 +19,5 @@
   box-sizing: border-box;
   overflow: hidden;
   margin:1%;
+  position: relative;
 }

+ 0 - 0
static/processing/测试负责流程/1.png → static/processing/测试复杂流程/1.png


+ 0 - 0
static/processing/测试负责流程/2.png → static/processing/测试复杂流程/2.png


+ 0 - 0
static/processing/测试负责流程/3.png → static/processing/测试复杂流程/3.png


+ 1 - 1
static/processing/测试负责流程/processing.json → static/processing/测试复杂流程/processing.json

@@ -1,6 +1,6 @@
 {
 	"actions": [
-		{"press": "1.png"},
+		{"string-press": "qq聊天测试群"},
 		{"press": "2.png"},
 		{"input": "测试信息"},
 		{"press": "3.png"}

TEMPAT SAMPAH
temp_screenshot.png