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

OpenCV二维码解码:如何获取二进制数据避免0x00截断?

解决OpenCV解码含0x00的二进制二维码数据被截断的问题

方案1:使用detectAndDecodeRaw函数

OpenCV的QRCodeDetector提供了detectAndDecodeRaw方法,它会直接返回解码后的原始字节数据,不会将其转换为字符串,因此不会出现0x00被当作字符串终止符截断的问题。

修改后的解码代码如下:

from time import sleep, time
import cv2

cap = cv2.VideoCapture("chun/video.mp4")
detector = cv2.QRCodeDetector()
c = 0
a = b''
while c != 32:
    _, img = cap.read()
    # 替换为detectAndDecodeRaw获取原始字节数据
    data, bbox, _ = detector.detectAndDecodeRaw(img)
    if a != data:
        print(data)
        a = data
    # cv2.imshow("QR file receiver", img)
    # c = cv2.waitKey(1)

cap.release()
cv2.destroyAllWindows()

该方法返回的是bytes类型数据,能完整保留包括0x00在内的所有二进制内容。

方案2:编码前对二进制数据做Base64转码

如果你的OpenCV版本较旧,没有detectAndDecodeRaw方法,可以在编码阶段先将二进制数据转成Base64字符串,规避0x00字节的问题,解码后再转回二进制。

编码端修改(基于qrcode库):

import qrcode
import base64

# 原始二进制数据
raw_data = b'meta\x00\x00\xf3\x43myfile.txt'
# 转成Base64字符串
b64_data = base64.b64encode(raw_data).decode('utf-8')
# 生成二维码
qr_img = qrcode.make(b64_data)
qr_img.save('qrcode.png')

解码端修改:

from time import sleep, time
import cv2
import base64

cap = cv2.VideoCapture("chun/video.mp4")
detector = cv2.QRCodeDetector()
c = 0
a = b''
while c != 32:
    _, img = cap.read()
    data, bbox, _ = detector.detectAndDecode(img)
    if data and a != data:
        # 将Base64字符串转回二进制数据
        raw_data = base64.b64decode(data)
        print(raw_data)
        a = data
    # cv2.imshow("QR file receiver", img)
    # c = cv2.waitKey(1)

cap.release()
cv2.destroyAllWindows()

这个方法兼容性更强,但Base64转码会使数据体积膨胀约33%。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 07:11:20