所需原料:opencv-python + yourmobilenet.caffemodel + yourdeploy.prototxt
利用opencv3.3.1之後推出的dnn模塊,支持很多模型的導入.這次我選擇Caffe的Mobilenet模型.
import numpy as np
import time
import cv2, os
print('******model*********')
net = cv2.dnn.readNetFromCaffe(r'./mobilenet_deploy.prototxt',
r'./model/mbilenet_iter_4055.caffemodel')
labels = [````]
cap = cv2.VideoCapture(0)
while 1:
_, frame1 = cap.read()
print('**********one frame***********')
frame = cv2.resize(frame1, (224,224)) # 你的網絡輸入的尺寸
# grab the frame dimensions and convert it to a blob
blob = cv2.dnn.blobFromImage(frame, 0.00390625, (224, 224), (112.24, 115.46, 117.84),swapRB=False)
net.setInput(blob)
detections = net.forward()
label = labels[np.argmax(detections)]
# label = str(np.argmax(detections))
cv2.putText(frame1, label,(111,111),cv2.FONT_HERSHEY_DUPLEX, 2, [0, 0, 111], 2)
# show the output frame
cv2.imshow("Frame", frame1)
cv2.waitKey(1)
blob = cv2.dnn.blobFromImage(frame, 0.00390625, (224, 224), (112.24, 115.46, 117.84),swapRB=False)
第二個參數是scale,第三個是送入網絡的尺寸,然後是每個通道的均值.