本文目录导读:

我来帮你创建一个二维码识别脚本,以下是使用Python和OpenCV的实现方法:
使用OpenCV(推荐,支持实时视频)
import cv2
import numpy as np
from pyzbar.pyzbar import decode
import sys
def decode_qr_from_image(image_path):
"""从图片文件识别二维码"""
# 读取图片
img = cv2.imread(image_path)
if img is None:
print(f"无法读取图片: {image_path}")
return
# 解码二维码
decoded_objects = decode(img)
for obj in decoded_objects:
print(f"二维码类型: {obj.type}")
print(f"二维码数据: {obj.data.decode('utf-8')}")
# 在图片上绘制边框
points = obj.polygon
if len(points) > 4:
hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))
points = hull
n = len(points)
for j in range(n):
cv2.line(img, tuple(points[j]), tuple(points[(j+1) % n]), (0, 255, 0), 3)
# 显示解码内容
x, y, w, h = obj.rect
cv2.putText(img, obj.data.decode('utf-8'), (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示结果
cv2.imshow("QR Code Decoder", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def decode_qr_from_camera():
"""从摄像头实时识别二维码"""
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("无法打开摄像头")
return
print("按 'q' 键退出")
while True:
ret, frame = cap.read()
if not ret:
break
# 解码二维码
decoded_objects = decode(frame)
for obj in decoded_objects:
# 绘制边框
points = obj.polygon
if len(points) > 4:
hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))
points = hull
n = len(points)
for j in range(n):
cv2.line(frame, tuple(points[j]), tuple(points[(j+1) % n]), (0, 255, 0), 3)
# 显示数据
x, y, w, h = obj.rect
data = obj.data.decode('utf-8')
cv2.putText(frame, data, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
print(f"识别到二维码: {data}")
# 显示视频
cv2.imshow("QR Code Scanner", frame)
# 按 'q' 退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
def decode_qr_from_screen():
"""从屏幕截图识别二维码(Windows)"""
try:
from PIL import ImageGrab
import pyautogui
except ImportError:
print("需要安装 Pillow 和 pyautogui")
print("pip install Pillow pyautogui")
return
print("程序将运行5秒,请将二维码放在屏幕上")
print("按 Ctrl+C 退出")
import time
for i in range(5):
# 截取屏幕
screen = ImageGrab.grab()
screen_np = np.array(screen)
screen_bgr = cv2.cvtColor(screen_np, cv2.COLOR_RGB2BGR)
# 解码
decoded_objects = decode(screen_bgr)
for obj in decoded_objects:
data = obj.data.decode('utf-8')
print(f"识别到二维码: {data}")
# 绘制边框
points = obj.polygon
if len(points) > 4:
hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))
points = hull
n = len(points)
for j in range(n):
cv2.line(screen_bgr, tuple(points[j]), tuple(points[(j+1) % n]), (0, 255, 0), 3)
cv2.imshow("Screen QR Scanner", screen_bgr)
cv2.waitKey(1)
time.sleep(1)
cv2.destroyAllWindows()
if __name__ == "__main__":
if len(sys.argv) > 1:
# 命令行参数处理
if sys.argv[1] == "camera":
decode_qr_from_camera()
elif sys.argv[1] == "screen":
decode_qr_from_screen()
else:
decode_qr_from_image(sys.argv[1])
else:
print("使用方法:")
print(" 识别图片: python qr_scanner.py image.jpg")
print(" 摄像头识别: python qr_scanner.py camera")
print(" 屏幕识别: python qr_scanner.py screen")
使用zbarlight(轻量级)
import zbarlight
from PIL import Image
def decode_qr_with_zbarlight(image_path):
"""使用zbarlight库识别二维码"""
try:
# 打开图片
with open(image_path, 'rb') as image_file:
image = Image.open(image_file)
image = image.convert('L') # 转换为灰度图
# 解码所有二维码
codes = zbarlight.scan_codes('qrcode', image)
if codes:
for code in codes:
print(f"二维码内容: {code.decode('utf-8')}")
else:
print("未识别到二维码")
except Exception as e:
print(f"识别失败: {e}")
def batch_decode_qr(folder_path):
"""批量识别文件夹中的二维码图片"""
import os
for filename in os.listdir(folder_path):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
filepath = os.path.join(folder_path, filename)
print(f"处理: {filename}")
decode_qr_with_zbarlight(filepath)
print("-" * 30)
安装依赖
# 主要依赖 pip install opencv-python pip install pyzbar pip install Pillow pip install numpy # 以下为可选 pip install zbarlight # 轻量级二维码识别 pip install pyautogui # 屏幕截图功能
使用示例
# 单张图片识别 python qr_scanner.py qrcode.jpg # 摄像头实时识别 python qr_scanner.py camera # 屏幕识别 python qr_scanner.py screen
高级功能版本
import cv2
import numpy as np
from pyzbar.pyzbar import decode
import json
import requests
from urllib.parse import urlparse
class AdvancedQRScanner:
def __init__(self):
self.scanned_codes = set() # 避免重复识别
def decode_qr(self, image):
"""解码二维码并返回详细结果"""
results = []
decoded_objects = decode(image)
for obj in decoded_objects:
data = obj.data.decode('utf-8')
# 避免重复识别
if data in self.scanned_codes:
continue
self.scanned_codes.add(data)
# 检测是否为URL
is_url = self.is_valid_url(data)
result = {
'data': data,
'type': obj.type,
'is_url': is_url,
'rect': {
'x': obj.rect.left,
'y': obj.rect.top,
'width': obj.rect.width,
'height': obj.rect.height
},
'points': [(p.x, p.y) for p in obj.polygon]
}
results.append(result)
# 如果是URL,可以自动访问
if is_url:
self.check_url_accessibility(data)
return results
def is_valid_url(self, text):
"""检查是否为有效URL"""
try:
result = urlparse(text)
return all([result.scheme, result.netloc])
except:
return False
def check_url_accessibility(self, url):
"""检查URL是否可访问"""
try:
response = requests.head(url, timeout=5)
print(f"URL状态: {response.status_code}")
except:
print(f"无法访问URL: {url}")
def save_results(self, results, filename='qr_results.json'):
"""保存识别结果到文件"""
with open(filename, 'w', encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"结果已保存到 {filename}")
def visualize_results(self, image, results):
"""在图片上可视化识别结果"""
for result in results:
points = result['points']
if len(points) > 4:
hull = cv2.convexHull(np.array(points, dtype=np.float32))
points = hull
n = len(points)
for j in range(n):
cv2.line(image, tuple(points[j]), tuple(points[(j+1) % n]), (0, 255, 0), 3)
x, y = result['rect']['x'], result['rect']['y']
cv2.putText(image, result['data'][:20] + '...' if len(result['data']) > 20 else result['data'],
(x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return image
# 使用示例
if __name__ == "__main__":
scanner = AdvancedQRScanner()
# 识别图片
img = cv2.imread("qrcode.jpg")
results = scanner.decode_qr(img)
for result in results:
print(f"识别到: {result['data']}")
print(f"类型: {result['type']}")
print(f"是否URL: {result['is_url']}")
# 保存结果
scanner.save_results(results)
这个脚本支持:
- 图片文件识别
- 摄像头实时识别
- 屏幕截图识别
- 批量处理
- 结果保存
- URL检测
- 避免重复识别
选择适合你需求的方案使用即可。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播