1. 检查系统环境

确保已安装 Python 3.8.9 并已将 Python 添加到系统 PATH 中。

打开命令提示符(以管理员身份运行),检查 Python 版本:

bash

python --version

升级pip,防止某些命令使用不了

# 升级pip到最新版本
 pip install --upgrade pip
python -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple

查看是否安装Visual C++ Redistributable

查看是否安装命令powershell执行

Get-Package -Name "Visual C++Redistributable*" | Format-Table -AutoSize

PS C:\Users\admin> Get-Package -Name "*Visual C++*Redistributable*" | Format-Table -AutoSize
​
Name                                                               Version       Source ProviderName
----                                                               -------       ------ ------------
Microsoft Visual C++ 2015-2019 Redistributable (x86) - 14.28.29913 14.28.29913.0        Programs
Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.44.35211 14.44.35211.0        Programs

如未安装,需下载安装,否则ocr识别无法使用

Visual C++ 运行库下载地址

# 下载并安装 Visual C++ 运行库
# 下载地址:https://aka.ms/vs/17/release/vc_redist.x64.exe
# 运行安装程序

2. 安装 NO_AVX 版本的 PaddlePaddle

因自身需求安装的no_avx版本的,测试可按需安装

系统可能不支持 AVX 指令集,需要安装专门的 no_avx 版本:注意2.4版本之后的就不支持noavx了

bash

​
pip install paddlepaddle==2.4.2 -f https://www.paddlepaddle.org.cn/whl/windows/mkl/noavx/stable.html
​

3. 验证 PaddlePaddle 安装

powershell执行

python -c "import paddle; print(paddle.__version__); paddle.utils.run_check()"

如果看到 "PaddlePaddle is installed successfully!" 表示安装成功。

使用脚本验证是否为no_avx版本

import paddle
import sys
import platform
​
print("=== PaddlePaddle 安装信息 ===")
print(f"PaddlePaddle版本: {paddle.__version__}")
print(f"安装路径: {paddle.__file__}")
print(f"Python版本: {sys.version}")
print(f"操作系统: {platform.system()} {platform.release()}")
​
print("\n=== 运行环境检查 ===")
try:
    # 检查是否使用了AVX
    paddle.set_device('cpu')
    print(f"设备设置: CPU")
    
    # 创建简单的张量
    x = paddle.to_tensor([1.0, 2.0, 3.0])
    print(f"张量创建成功: {x}")
    print(f"张量值: {x.numpy()}")
    
    # 测试矩阵运算
    a = paddle.randn([3, 3])
    b = paddle.randn([3, 3])
    c = paddle.matmul(a, b)
    print(f"矩阵乘法测试成功,结果形状: {c.shape}")
    
    # 检查编译选项(新方法)
    print(f"是否使用GPU编译: {paddle.is_compiled_with_cuda()}")
    
    # 查看版本详细信息
    print(f"\nPaddle版本详细信息:")
    print(f"  版本号: {paddle.version.full_version}")
    print(f"  提交号: {paddle.version.commit}")
    
    print("\n✅ PaddlePaddle运行正常")
    print("📝 这很可能就是no_avx版本(因为能正常运行)")
    
except Exception as e:
    print(f"✗ 运行出错: {e}")

4. 安装 PaddleOCR

bash

# 安装 PaddleOCR
pip install paddleocr==2.6.1.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
​
​
# 如果需要使用版面分析功能,还需要安装 layoutparser
pip install layoutparser -i https://pypi.tuna.tsinghua.edu.cn/simple

5. 安装其他依赖

bash

# 安装必要的图像处理库
pip install opencv-python pillow shapely pyclipper lmdb tqdm numpy pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple
​
# 如果遇到 Visual C++ 14.0 错误,可以安装预编译的 opencv
pip install opencv-python==4.6.0.66 -i https://pypi.tuna.tsinghua.edu.cn/simple

6. 验证 PaddleOCR 安装

创建一个测试文件 test_ocr.py:识别速度与avx版本的存在差异

python

"""
修复版文本查找和点击工具 - 使用与调试相同的参数
"""
​
import pyautogui
import cv2
import numpy as np
import time
from PIL import ImageGrab
from paddleocr import PaddleOCR
​
​
class TextClickerFixed:
    def __init__(self):
        """初始化"""
        self.ocr = None
        self.screen_size = pyautogui.size()
        print(f"屏幕分辨率: {self.screen_size.width}x{self.screen_size.height}")
    
    def init_ocr(self):
        """初始化OCR(使用调试相同的参数)"""
        if self.ocr is None:
            try:
                self.ocr = PaddleOCR(
                    use_angle_cls=False,
                    lang='ch',
                    use_gpu=False,
                    enable_mkldnn=True,
                    show_log=False,  # 可以改为True查看识别过程
                    det_limit_side_len=self.screen_size.height,  # 使用屏幕高度
                    det_db_thresh=0.1,       # 与调试相同
                    det_db_box_thresh=0.1,   # 添加这个参数
                    det_db_unclip_ratio=1.6, # 扩大检测框
                    max_text_length=100,
                    use_space_char=True,
                    drop_score=0.5,
                )
                print("OCR引擎已初始化(使用调试参数)")
            except Exception as e:
                print(f"OCR初始化失败: {e}")
                raise
        return self.ocr
    
    def capture_screen(self, region=None):
        """截图"""
        start_time = time.time()
        
        if region is None:
            # 截取全屏
            screenshot = ImageGrab.grab()
            capture_region = (0, 0, self.screen_size.width, self.screen_size.height)
        else:
            screenshot = ImageGrab.grab(bbox=region)
            capture_region = region
        
        # 转换为OpenCV格式
        img_cv = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
        
        # 记录耗时
        capture_time = time.time() - start_time
        print(f"截图耗时: {capture_time:.3f}秒")
        
        return img_cv, capture_region
    
    def find_text_position_debug(self, target_text, region=None, confidence=0.1):
        """
        查找文本位置(带详细调试信息)
        """
        print(f"\n🔍 详细查找: '{target_text}'")
        print(f"置信度阈值: {confidence}")
        
        total_start = time.time()
        
        try:
            # 1. 截图
            screenshot_start = time.time()
            img_cv, capture_region = self.capture_screen(region)
            screenshot_time = time.time() - screenshot_start
            
            # 2. OCR识别
            ocr_start = time.time()
            ocr = self.init_ocr()
            result = ocr.ocr(img_cv, cls=False)
            ocr_time = time.time() - ocr_start
            
            print(f"OCR返回 {len(result)} 组结果")
            
            # 3. 查找目标文本(带详细输出)
            find_start = time.time()
            best_match = None
            best_confidence = 0
            match_count = 0
            
            for res_idx, res in enumerate(result):
                if res:
                    print(f"\n第{res_idx}组,有{len(res)}个识别结果:")
                    for line_idx, line in enumerate(res):
                        text = line[1][0]
                        conf = line[1][1]
                        
                        # 检查是否包含目标文本
                        contains_target = target_text in text
                        meets_confidence = conf >= confidence
                        
                        print(f"  [{line_idx}] 文本: '{text}'")
                        print(f"       置信度: {conf:.3f}")
                        print(f"       包含'{target_text}': {contains_target}")
                        print(f"       通过置信度: {meets_confidence}")
                        
                        if contains_target and meets_confidence:
                            match_count += 1
                            print(f"       ✅ 匹配成功!")
                            
                            if conf > best_confidence:
                                # 计算中心坐标
                                points = line[0]
                                x_center = sum(p[0] for p in points) / 4
                                y_center = sum(p[1] for p in points) / 4
                                
                                best_match = {
                                    'x': int(x_center),
                                    'y': int(y_center),
                                    'text': text,
                                    'confidence': conf,
                                    'region': capture_region,
                                    'raw_points': points
                                }
                                best_confidence = conf
                                print(f"       坐标: ({int(x_center)}, {int(y_center)})")
            
            find_time = time.time() - find_start
            total_time = time.time() - total_start
            
            if best_match:
                print(f"\n✅ 找到 {match_count} 个匹配,最佳匹配:")
                print(f"   文本: '{best_match['text']}'")
                print(f"   置信度: {best_match['confidence']:.3f}")
                print(f"   屏幕坐标: ({best_match['x']}, {best_match['y']})")
                print(f"   耗时: 截图={screenshot_time:.3f}s, OCR={ocr_time:.3f}s, "
                      f"查找={find_time:.3f}s, 总计={total_time:.3f}s")
                return best_match
            else:
                print(f"\n❌ 未找到文本: '{target_text}'")
                print(f"   检查了 {sum(len(r) for r in result if r)} 个识别结果")
                print(f"   耗时: 截图={screenshot_time:.3f}s, OCR={ocr_time:.3f}s, "
                      f"查找={find_time:.3f}s, 总计={total_time:.3f}s")
                return None
                
        except Exception as e:
            print(f"❌ 查找过程出错: {e}")
            import traceback
            traceback.print_exc()
            return None
    
    def click_text_fixed(self, target_text, region=None, click_type='double', confidence=0.1):
        """
        修复版:查找文本并点击
        """
        print(f"\n{'='*60}")
        print(f"开始查找并点击: '{target_text}'")
        print(f"点击类型: {click_type}, 置信度阈值: {confidence}")
        print(f"{'='*60}")
        
        total_start = time.time()
        
        # 查找文本位置(使用调试版)
        result = self.find_text_position_debug(target_text, region, confidence)
        
        if result:
            x, y = result['x'], result['y']
            
            try:
                print(f"\n准备点击...")
                print(f"目标坐标: ({x}, {y})")
                print(f"当前鼠标位置: {pyautogui.position()}")
                
                # 移动到目标位置
                move_start = time.time()
                pyautogui.moveTo(x, y, duration=0.3)
                move_time = time.time() - move_start
                
                print(f"移动后位置: {pyautogui.position()}")
                
                # 等待一下
                time.sleep(0.2)
                
                # 执行点击
                click_start = time.time()
                
                if click_type == 'left' or click_type == 'single':
                    pyautogui.click()
                    click_action = "单击"
                elif click_type == 'double':
                    pyautogui.doubleClick()
                    click_action = "双击"
                elif click_type == 'right':
                    pyautogui.rightClick()
                    click_action = "右击"
                else:
                    pyautogui.click()
                    click_action = "单击"
                
                click_time = time.time() - click_start
                
                # 计算总耗时
                total_time = time.time() - total_start
                
                print(f"\n✅ 点击完成!")
                print(f"   点击类型: {click_action}")
                print(f"   点击坐标: ({x}, {y})")
                print(f"   耗时统计: 移动={move_time:.3f}s, 点击={click_time:.3f}s, 总计={total_time:.3f}s")
                print(f"{'='*60}")
                
                return True
                
            except Exception as e:
                print(f"❌ 点击过程出错: {e}")
                import traceback
                traceback.print_exc()
                return False
        else:
            print(f"\n❌ 无法点击,未找到文本: '{target_text}'")
            print(f"{'='*60}")
            return False
    
    def test_ocr_recognition(self):
        """测试OCR识别功能"""
        print("\n" + "="*60)
        print("测试OCR识别功能")
        print("="*60)
        
        # 截图
        img_cv, region = self.capture_screen()
        
        # OCR识别
        ocr = self.init_ocr()
        result = ocr.ocr(img_cv, cls=False)
        
        # 显示所有识别结果
        all_texts = []
        for res in result:
            if res:
                for line in res:
                    text = line[1][0]
                    conf = line[1][1]
                    all_texts.append((text, conf))
        
        print(f"\n总共识别到 {len(all_texts)} 个文本:")
        print("-"*60)
        
        # 按置信度排序
        all_texts.sort(key=lambda x: x[1], reverse=True)
        
        for i, (text, conf) in enumerate(all_texts[:20]):  # 显示前20个
            print(f"{i+1:2d}. '{text}' (置信度: {conf:.3f})")
        
        # 检查是否有"整理"
        print(f"\n检查是否包含'整理':")
        for text, conf in all_texts:
            if "整理" in text:
                print(f"✅ 找到: '{text}' (置信度: {conf:.3f})")
        
        return all_texts
​
​
# ========================= 使用示例 =========================
if __name__ == "__main__":
    # 创建点击器
    clicker = TextClickerFixed()
    
    # 初始化OCR
    clicker.init_ocr()
    
    print("\n" + "="*60)
    print("修复版文本点击工具")
    print("="*60)
    
    # 先测试OCR识别
    print("\n第一步:测试OCR识别...")
    clicker.test_ocr_recognition()
    
    time.sleep(1)
    
    # 尝试点击"整理"
    '''print("\n第二步:尝试点击'整理'...")
    success = clicker.click_text_fixed("整理", click_type='double', confidence=0.1)
    
    if success:
        print("\n✅ 成功点击'整理'!")
        
        # 等待文件打开
        time.sleep(2)
        
        # 然后尝试点击打开窗口中的"文件"
        print("\n第三步:尝试点击打开窗口中的'文件'...")
        clicker.click_text_fixed("文件", click_type='left', confidence=0.1)
    else:
        print("\n❌ 未能点击'整理'")
        
        # 尝试其他可能
        print("\n尝试其他可能的文本...")
        possible_texts = ["整理,txt", "整理.txt", "整理", "理", "整"]
        
        for text in possible_texts:
            print(f"\n尝试查找: '{text}'")
            result = clicker.find_text_position_debug(text, confidence=0.05)
            if result:
                print(f"✅ 找到 '{text}',尝试点击...")
                x, y = result['x'], result['y']
                pyautogui.moveTo(x, y, duration=0.3)
                pyautogui.doubleClick()
                break'''
    time.sleep(2)
    success = clicker.click_text_fixed("帮助", click_type='left', confidence=0.1)
    print("\n" + "="*60)
    print("程序结束")

更多推荐