在OpenCV中,可以使用cv2.dnn
模塊來構建和使用卷積神經網絡(CNN)。首先,你需要下載預訓練的模型文件(如Caffe模型文件)和相應的標簽文件。然后,你可以使用以下步驟來加載模型并進行推理:
import cv2
import numpy as np
model_file = "path/to/model_file.prototxt"
weights_file = "path/to/weights_file.caffemodel"
label_file = "path/to/label_file.txt"
net = cv2.dnn.readNetFromCaffe(model_file, weights_file)
classes = open(label_file).read().strip().split("\n")
image = cv2.imread("path/to/image.jpg")
blob = cv2.dnn.blobFromImage(image, 1.0, (224, 224), (104.0, 177.0, 123.0))
net.setInput(blob)
detections = net.forward()
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
class_id = int(detections[0, 0, i, 1])
label = f"{classes[class_id]}: {confidence:.2f}%"
cv2.putText(image, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
這樣,你就可以使用OpenCV中的cv2.dnn
模塊來構建和使用卷積神經網絡了。注意,這只是一個簡單的示例,實際應用中可能需要根據具體情況進行調整和優化。