OpenCV 学习资料——第四章:OpenCV中的机器学习与深度学习应用

第四章:OpenCV中的机器学习与深度学习应用


4.1 机器学习基础

OpenCV集成了一些经典的机器学习算法,提供了灵活的接口用于分类、回归和聚类任务。

4.1.1 K近邻(KNN)

KNN是一种简单的分类算法,通过计算样本与训练数据的距离进行分类。

 
 

python

import numpy as np
import cv2

# 准备数据
train_data = np.random.randint(0, 100, (25, 2)).astype(np.float32)
labels = np.random.randint(0, 2, (25, 1)).astype(np.float32)

# 创建KNN模型
knn = cv2.ml.KNearest_create()
knn.train(train_data, cv2.ml.ROW_SAMPLE, labels)

# 测试数据
test_data = np.random.randint(0, 100, (10, 2)).astype(np.float32)
ret, results, neighbours, dist = knn.findNearest(test_data, k=3)
print(f"Results: {results.ravel()}")

4.1.2 支持向量机(SVM)

SVM适用于分类和回归问题,通过最大化类别间的间隔来寻找决策边界。

 
 

python

# 训练数据
train_data = np.array([[1, 2], [2, 3], [3, 3], [4, 5], [6, 7], [7, 8]], dtype=np.float32)
labels = np.array([0, 0, 1, 1, 2, 2], dtype=np.int32)

# 创建SVM模型
svm = cv2.ml.SVM_create()
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.setType(cv2.ml.SVM_C_SVC)
svm.train(train_data, cv2.ml.ROW_SAMPLE, labels)

# 测试数据
test_data = np.array([[3, 3]], dtype=np.float32)
_, result = svm.predict(test_data)

print(f"Prediction: {result}")

4.2 深度学习在OpenCV中的应用

OpenCV提供了dnn模块,可以加载和使用预训练的深度学习模型(如Caffe、TensorFlow、PyTorch、ONNX等)。

4.2.1 加载预训练模型

1. 加载Caffe模型
 
 

python

# 加载模型
net = cv2.dnn.readNetFromCaffe("deploy.prototxt", "weights.caffemodel")

# 图像预处理
blob = cv2.dnn.blobFromImage(img, scalefactor=1.0, size=(224, 224), mean=(104, 117, 123))

# 前向传播
net.setInput(blob)
output = net.forward()
print(f"Output: {output}")
2. 加载TensorFlow模型
 
 

python

net = cv2.dnn.readNetFromTensorflow("model.pb", "model.pbtxt")

4.2.2 深度学习模型的常见应用

1. 图像分类

使用预训练的分类网络(如MobileNet、ResNet)。

 
 

python

net = cv2.dnn.readNetFromONNX("mobilenet.onnx")
blob = cv2.dnn.blobFromImage(img, scalefactor=1.0/255, size=(224, 224))
net.setInput(blob)
output = net.forward()
print(f"Class: {np.argmax(output)}")
2. 目标检测

使用YOLO或SSD进行目标检测。

 
 

python

net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
blob = cv2.dnn.blobFromImage(img, scalefactor=1/255.0, size=(416, 416))
net.setInput(blob)
layer_names = net.getUnconnectedOutLayersNames()
outputs = net.forward(layer_names)

for output in outputs:
    for detection in output:
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]
        if confidence > 0.5:
            print(f"Class: {class_id}, Confidence: {confidence}")
3. 实时人脸检测

使用DNN模块加载人脸检测模型。

 
 

python

net = cv2.dnn.readNetFromCaffe("deploy.prototxt", "res10_300x300_ssd_iter_140000.caffemodel")
blob = cv2.dnn.blobFromImage(img, scalefactor=1.0, size=(300, 300), mean=(104, 117, 123))
net.setInput(blob)
detections = net.forward()

for i in range(detections.shape[2]):
    confidence = detections[0, 0, i, 2]
    if confidence > 0.5:
        box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
        x1, y1, x2, y2 = box.astype("int")
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)