计算机视觉入门:用OpenCV做AI图像识别

📘 AI教程 💬 🔥 Trending 发布者: leakey
计算机视觉入门:用OpenCV做AI图像识别

🩺 摘要

想用AI做图像识别——识别图片里的物体、人脸、文字。从哪开始?

📝 详情

OpenCV + AI:2026年计算机视觉快速入门实战

环境搭建对比

组件 版本 安装命令 大小
OpenCV 4.10+ pip install opencv-python ~30MB
HuggingFace Transformers 4.48+ pip install transformers ~15MB
PyTorch 2.5+ pip install torch ~800MB(含CUDA)

第一步:OpenCV基础操作

import cv2
import numpy as np

# 读取图片
img = cv2.imread('photo.jpg')
print(f"图片尺寸: {img.shape}")  # (高度, 宽度, 通道数)

# 转灰度(减少计算量)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 边缘检测(Canny算法,阈值可调)
edges = cv2.Canny(gray, 50, 150)

# 显示并保存
cv2.imshow('Original', img)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('edges_output.jpg', edges)

第二步:AI模型做图像分类

from transformers import pipeline

# 加载预训练模型(首次下载约500MB)
classifier = pipeline("image-classification", model="google/vit-base-patch16-224")

result = classifier("photo.jpg")
print(result)
# 输出:[{'label': 'golden retriever', 'score': 0.95}, ...]

算法性能对比

任务 传统OpenCV方法 AI模型方法 准确率提升
物体识别 SIFT + 特征匹配(~60%) ResNet50/ViT(>90%) +30%
人脸检测 Haar Cascade(~80%) MTCNN/RetinaFace(>99%) +19%
文字识别 Tesseract 中英混合(~70%) PaddleOCR 中英混合(>95%) +25%

第三步:实战——实时人脸检测

import cv2
from facenet_pytorch import MTCNN
import torch

device = 'cuda' if torch.cuda.is_available() else 'cpu'
detector = MTCNN(keep_all=True, device=device)

cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    if not ret:
        break
    boxes, probs = detector.detect(frame)
    if boxes is not None:
        for box, prob in zip(boxes, probs):
            if prob > 0.9:
                x1, y1, x2, y2 = [int(v) for v in box]
                cv2.rectangle(frame, (x1,y1), (x2,y2), (0,255,0), 2)
                cv2.putText(frame, f'{prob:.2f}', (x1,y1-10),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
    cv2.imshow('Face Detection', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

第四步:OCR文字识别

from paddleocr import PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='ch')
result = ocr.ocr('receipt.jpg')
for line in result[0]:
    print(f"文字: {line[1][0]}, 置信度: {line[1][1]:.2f}")
# 输出:
# 文字: 收款收据, 置信度: 0.98
# 文字: 金额: ¥1,280.00, 置信度: 0.96

性能基准(RTX 3060,1000张图片)

  • ViT分类:~50ms/张 | 准确率92%
  • MTCNN人脸检测:~30ms/张 | 召回率99.2%
  • Haar Cascade:~5ms/张 | 召回率80%
  • PaddleOCR:~200ms/张 | 准确率95%+

实践建议

  1. 简单任务用OpenCV传统方法(快、小、准),复杂任务用AI模型
  2. 先用小模型验证流程,再换大模型提升精度
  3. GPU推理比CPU快5-20倍,但首次加载模型较慢