吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 631|回复: 3
收起左侧

[Python 转载] [更新]百度网盘下载二维码链接识别Ver1.1

[复制链接]
flashgetme 发表于 2026-9-20 11:22
更新原因:日常使用中,发现有部分网站的二维码识别失效,原因不明,截图后没法正常获得链接,推测可能二维码部分识别有问题导致。
更新内容:与原代码相比,改动集中在二维码识别部分,其余(截图、选图、链接解析、GUI)未变。具体如下:
1. 删除 preprocess_image 函数(原 21-25 行) 原函数:灰度 → 中值滤波 → OTSU 阈值,只生成一张图。
2. 新增 preprocess_variants(img) 函数 把预处理改为生成多张候选图:原图、灰度图、、TSU 二值化图、反色图(cv2.bitwise_not)— 解决反色二维码、CLAHE 对比度增强图 — 解决低对比度
    若宽或高 < 500,额外生成放大 2 倍、3 倍图 — 解决小图/低分辨率
3. 重写 decode_qr_cv2(img) 函数(原 16-19 行)
   原来:只对单张图调用一次 detectAndDecode。
   现在:遍历所有候选图依次 detectAndDecode,任一成功即返回;最后用 detectAndDecodeMulti 兜底检测多个/边缘二维码,失败则返回 None。
4. 两处调用点简化
decode_qr_from_capture:decode_qr_cv2(processed) or decode_qr_cv2(img) → decode_qr_cv2(img)
decode_qr_from_image:同上简化
效果:无需新依赖,覆盖模糊、太小、反色、低对比度导致的识别失败场景。

界面截图:
ScreenShot_2026-09-20_111711_718.png

[Python] 纯文本查看 复制代码
import cv2
import numpy as np
import PySimpleGUI as sg
import pyperclip
from PIL import ImageGrab, Image
import re
from ctypes import windll

sg.theme('LightBlue2')
user32 = windll.user32
screen_width = user32.GetSystemMetrics(0)
screen_height = user32.GetSystemMetrics(1)

crop_result = None

def preprocess_variants(img):
    variants = [img]
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    variants.append(cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR))
    blurred = cv2.medianBlur(gray, 3)
    _, binary = cv2.threshold(blurred, 120, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    variants.append(cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR))
    variants.append(cv2.cvtColor(cv2.bitwise_not(binary), cv2.COLOR_GRAY2BGR))
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    variants.append(cv2.cvtColor(clahe.apply(gray), cv2.COLOR_GRAY2BGR))
    if img.shape[0] < 500 or img.shape[1] < 500:
        for scale in (2, 3):
            upscaled = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
            variants.append(upscaled)
    return variants

def decode_qr_cv2(img):
    qr_detector = cv2.QRCodeDetector()
    for variant in preprocess_variants(img):
        data, bbox, _ = qr_detector.detectAndDecode(variant)
        if data:
            return data
    try:
        data, _, _, _ = qr_detector.detectAndDecodeMulti(img)
        if data:
            return data[0]
    except cv2.error:
        pass
    return None

def mouse_event(event, x, y, flags, param):
    global ix, iy, drawing, img_copy, full_screen, crop_result
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            img_copy = full_screen.copy()
            cv2.rectangle(img_copy, (ix, iy), (x, y), (0, 255, 0), 2)
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        x1, y1 = min(ix, x), min(iy, y)
        x2, y2 = max(ix, x), max(iy, y)
        if x2 - x1 > 10 and y2 - y1 > 10:
            crop_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
            crop_result = cv2.cvtColor(np.array(crop_img), cv2.COLOR_RGB2BGR)
        cv2.destroyAllWindows()

def screen_capture():
    global ix, iy, drawing, img_copy, full_screen, crop_result
    ix, iy = -1, -1
    drawing = False
    crop_result = None

    full_screen = np.array(ImageGrab.grab(bbox=(0, 0, screen_width, screen_height)))
    full_screen = cv2.cvtColor(full_screen, cv2.COLOR_RGB2BGR)
    img_copy = full_screen.copy()

    alpha = 0.3
    overlay = full_screen.copy()
    cv2.addWeighted(overlay, alpha, full_screen, 1 - alpha, 0, full_screen)

    cv2.namedWindow("screen_capture", cv2.WND_PROP_FULLSCREEN)
    cv2.setWindowProperty("screen_capture", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
    cv2.setMouseCallback("screen_capture", mouse_event)

    while True:
        cv2.imshow("screen_capture", img_copy)
        key = cv2.waitKey(1) & 0xFF
        if key == 27:
            crop_result = None
            break
        if cv2.getWindowProperty("screen_capture", cv2.WND_PROP_VISIBLE) < 1:
            break

    cv2.destroyAllWindows()
    return crop_result

def decode_qr_from_capture():
    try:
        img = screen_capture()
        if img is None:
            return None, "已取消截图"
        data = decode_qr_cv2(img)
        if data:
            return data, "&#9989; 识别成功"
        else:
            return None, "&#10060; 未检测到二维码"
    except Exception as e:
        return None, f"错误:{str(e)}"

def decode_qr_from_image(img_path):
    try:
        img = cv2.imread(img_path)
        if img is None:
            return None, "&#10060; 无法读取图片"
        data = decode_qr_cv2(img)
        return (data, "&#9989; 识别成功") if data else (None, "&#10060; 未检测到二维码")
    except Exception as e:
        return None, f"错误:{str(e)}"

def parse_baidu_link(text):
    result = {"link": "", "code": ""}
    link_match = re.search(r'https://pan\.baidu\.com/[^\s]+', text)
    if link_match:
        result["link"] = link_match.group(0)

    pwd_match = re.search(r'pwd=([A-Za-z0-9]{4})', text)
    if pwd_match:
        result["code"] = pwd_match.group(1).upper()
    else:
        code_match = re.search(r'[提取码]*[::]\s*([A-Za-z0-9]{4})', text)
        if code_match:
            result["code"] = code_match.group(1).upper()
    return result

layout = [
    [sg.Text("百度网盘二维码识别工具", font=("微软雅黑", 14, "bold"))],
    [sg.HorizontalSeparator()],
    [sg.Button("选择图片识别", size=(15, 1)),
     sg.Button("屏幕截图识别", size=(15, 1))],
    [sg.Text("_" * 50)],
    [sg.Text("识别结果:")],
    [sg.Multiline(size=(50, 4), key="-RESULT-", disabled=True)],
    [sg.Text("网盘链接:"), sg.Input(key="-LINK-", size=(40, 1), disabled=True)],
    [sg.Text("提取码:"), sg.Input(key="-CODE-", size=(10, 1), disabled=True), sg.Button("复制全部")],
    [sg.Text("", key="-STATUS-", text_color="red", size=(50, 1))]
]

window = sg.Window("百度网盘二维码识别", layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break

    if event == "选择图片识别":
        file_path = sg.popup_get_file("选择二维码图片", file_types=(("图片", "*.png;*.jpg;*.jpeg;*.bmp"),))
        if file_path:
            qr_data, status = decode_qr_from_image(file_path)
            window["-STATUS-"].update(status)
            if qr_data:
                window["-RESULT-"].update(qr_data)
                bd = parse_baidu_link(qr_data)
                window["-LINK-"].update(bd["link"])
                window["-CODE-"].update(bd["code"])

    if event == "屏幕截图识别":
        window.Hide()
        qr_data, status = decode_qr_from_capture()
        window.UnHide()
        window["-STATUS-"].update(status)
        if qr_data:
            window["-RESULT-"].update(qr_data)
            bd = parse_baidu_link(qr_data)
            window["-LINK-"].update(bd["link"])
            window["-CODE-"].update(bd["code"])

    if event == "复制全部":
        link = values["-LINK-"]
        code = values["-CODE-"]
        if link and code:
            pyperclip.copy(f"链接:{link}\n提取码:{code}")
            window["-STATUS-"].update("&#9989; 已复制到剪贴板")
        elif link:
            pyperclip.copy(link)
            window["-STATUS-"].update("&#9989; 已复制链接")

window.close()

免费评分

参与人数 2吾爱币 +8 热心值 +1 收起 理由
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
zjm93202767 + 1 我很赞同!

查看全部评分

发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

longzekai 发表于 2026-9-20 23:09
虽然现在用不上,但是必须赞一个。
rose521rain 发表于 2026-9-20 23:44
本帖最后由 rose521rain 于 2026-9-20 23:58 编辑

不知道为什么,我识别不了。
 楼主| flashgetme 发表于 2026-9-21 08:22
rose521rain 发表于 2026-9-20 23:44
不知道为什么,我识别不了。

试一下这个新版,旧版的确有一些是识别不了的。新版的识别率已经比较高了。另外注意截图的大小不要选得太大了。有时候我感觉沿着二维码的四条白边拉框识别率会高一些。或反复多截图几次。实在不行就截成图片再读入让程序识别。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-11-11 08:58

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表