1. 程式人生 > 實用技巧 >Python 用dlib來實現視訊人臉檢測 (很卡,我電腦帶不動,卡死了。。)我的是輕薄本

Python 用dlib來實現視訊人臉檢測 (很卡,我電腦帶不動,卡死了。。)我的是輕薄本

電腦好的可以試試,比opencv效果好多了,畢竟訓練模型都有60mb,速度慢。

程式碼:

import cv2
import dlib

def CatchPICFromVideo(camera_idx):
    cv2.namedWindow("image",0)
    #qcv2.resizeWindow("image", 1600, 900)  # 設定長和寬
    # 視訊來源,可以來自一段已存好的視訊,也可以直接來自USB攝像頭
    cap = cv2.VideoCapture(camera_idx)
    num = 0
    while cap.isOpened():
        ok, frame1 
= cap.read() # 讀取一幀資料 scale_percent = 10 # percent of original size 縮小到原來25% width = int(frame1.shape[1] * scale_percent / 100) height = int(frame1.shape[0] * scale_percent / 100) dim = (width, height) frame = cv2.resize(frame1, dim, interpolation=cv2.INTER_AREA)
if not ok: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 人臉分類器 detector = dlib.get_frontal_face_detector() # 獲取人臉檢測器 predictor = dlib.shape_predictor( "shape_predictor_68_face_landmarks.dat" ) color = (0, 255, 0) #
定義繪製顏色 dets = detector(gray, 1) if len(dets) > 0: # 大於0則檢測到人臉 for face in dets: shape = predictor(frame, face) # 尋找人臉的68個標定點 chang = [] kuan = [] # 遍歷所有點,打印出其座標,並圈出來 for pt in shape.parts(): #pt_pos = (pt.x, pt.y) chang.append(pt.x) kuan.append(pt.y) #cv2.circle(img, pt_pos, 1, (0, 255, 0), 1) num += 1 #if num > catch_pic_num: # 如果超過指定最大儲存數量退出迴圈 #break # 畫出矩形框 x1 = max(chang) x2 = min(chang) y1 = max(kuan) y2 = min(kuan) cv2.rectangle(frame, (x2, y2), (x1, y1), color, 2) #cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2) # 顯示當前捕捉到了多少人臉圖片了,這樣站在那裡被拍攝時心裡有個數,不用兩眼一抹黑傻等著 #font = cv2.FONT_HERSHEY_SIMPLEX #cv2.putText(frame ,'num:%d' % (num) ,(x2 + 30, y2 + 30), font, 1, (255 ,0 ,255) ,4) # 超過指定最大儲存數量結束程式 #if num > catch_pic_num: #break # 顯示影象 cv2.imshow("image", frame) c = cv2.waitKey(1) if c & 0xFF == ord('q'): break # 釋放攝像頭並銷燬所有視窗 cap.release() cv2.destroyAllWindows() print(CatchPICFromVideo(r'H:\renwu__opencv\zhaopian\IMG_1502.MOV'))

直接卡死了。。就不放效果圖了。