You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本实现CR2格式RAW文件二维码检测与数据提取求助

处理Canon CR2文件二维码检测的Python脚本及Automator配置

一、依赖安装

首先安装处理RAW文件和二维码检测的库,打开终端运行:

brew install libraw  # macOS下安装rawpy依赖的底层库
pip install rawpy opencv-python numpy

二、Python脚本实现

import rawpy
import cv2
import numpy as np
from pathlib import Path
import sys

def detect_qr_from_cr2(cr2_path):
    """读取CR2文件并检测二维码"""
    try:
        # 读取CR2 RAW文件,提取RGB数据
        with rawpy.imread(str(cr2_path)) as raw:
            # 将RAW数据转成8位RGB图像
            rgb_img = raw.postprocess(output_bps=8)
        # OpenCV默认用BGR格式,转换格式适配
        bgr_img = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2BGR)
        
        # 初始化二维码检测器
        qr_detector = cv2.QRCodeDetector()
        # 检测并解码二维码
        data, points, _ = qr_detector.detectAndDecode(bgr_img)
        
        if data:
            print(f"文件 {cr2_path.name} 中检测到二维码:")
            print(f"内容: {data}")
            if points is not None:
                print(f"二维码位置: {points}")
        else:
            print(f"文件 {cr2_path.name} 中未检测到二维码")
    except Exception as e:
        print(f"处理文件 {cr2_path.name} 时出错: {str(e)}")

def main():
    # 从Automator获取传入的文件夹路径
    if len(sys.argv) < 2:
        print("请选择要处理的文件夹")
        return
    # 遍历传入的所有路径(支持多选文件夹)
    for folder_path in sys.argv[1:]:
        folder = Path(folder_path)
        if not folder.is_dir():
            print(f"{folder_path} 不是有效的文件夹路径")
            continue
        # 查找所有CR2文件(不区分大小写)
        cr2_files = list(folder.glob("*.CR2")) + list(folder.glob("*.cr2"))
        if not cr2_files:
            print(f"文件夹 {folder.name} 中未找到CR2文件")
            continue
        print(f"开始处理文件夹 {folder.name} 中的CR2文件...")
        for cr2_file in cr2_files:
            detect_qr_from_cr2(cr2_file)

if __name__ == "__main__":
    main()

三、配置Automator应用

  1. 打开Automator,选择新建应用程序
  2. 在左侧动作库中搜索并添加运行Shell脚本动作
  3. 在脚本设置中:
    • 选择**/usr/bin/python3**作为Shell
    • 选择将输入作为自变量传递
  4. 将上面的Python脚本完整粘贴到脚本输入框中
  5. 保存应用(比如命名为"CR2二维码检测")

使用时,直接将目标文件夹拖到这个Automator应用图标上,脚本就会自动遍历文件夹内的CR2文件并检测二维码。

注意事项

  • 如果安装rawpy时出错,确保已经安装了libraw(macOS用brew,Linux用apt-get install libraw-dev)
  • 部分CR2文件可能因损坏或格式特殊无法读取,脚本会捕获异常并提示
  • 二维码需要清晰可见,RAW转成的图像如果分辨率过高,检测速度会变慢,可根据需要在postprocess中添加resize参数降低分辨率(比如resize=(1920,1080))

内容的提问来源于stack exchange,提问作者JBS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:00:09