Python 用opencv實現人臉檢測 另一種寫法
阿新 • • 發佈:2020-10-23
程式碼:
import sys import cv2 def _help(): print("Usage:") print(" python video_face_detect_cv.py") print(" python video_face_detect_cv.py <path of a video>") print("For example:") print(" python video_face_detect_cv.py video/lee.mp4") print("If the path of a video is not provided, the camera will be used as the input.Press q to quit.") def _face_detect(color_image, detector): # 將彩色圖片轉換為灰色 gray_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY) # 用detector檢測人臉 face_rects = detector.detectMultiScale(gray_image, scaleFactor=1.2, minNeighbors=3, minSize=(100, 100)) color = (0, 0, 255) # 定義繪製顏色為紅色 line_width = 2 #定義繪圖線寬為2 if (len(face_rects)) > 0: for face_rect in face_rects: x, y, w, h = face_rect # (x,y)是矩陣左上角的座標,w是矩陣的寬,h是矩陣的高 cv2.rectangle(color_image, (x, y), (x + w, y + h), color, line_width) cv2.namedWindow("Image", cv2.WINDOW_NORMAL) cv2.imshow("Image", color_image)def face_detect(video_path=0): """ 思路:把視訊逐幀分解成圖片,基於圖片檢測標識出人臉的位置,把處理的圖片逐幀繪製給使用者 """ # 獲取OpenCV人臉識別分類器 detector = cv2.CascadeClassifier("D:\Study\python__gongju\opencv-master/data/haarcascades/haarcascade_frontalface_default.xml") # 獲取視訊或者攝像頭輸入流 video = 1 # 0代表筆記本自帶攝像頭 1代表外接的攝像頭比如iVCam 也可以地址 比如IP攝像頭 cap = cv2.VideoCapture(video) # 逐幀顯示 while True: ret, img = cap.read() if img is None: break _face_detect(img, detector) # 如果輸入的是“q”,則跳出迴圈結束檢測 if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() # 釋放攝像頭 cv2.destroyAllWindows() if len(sys.argv) > 2 or "-h" in sys.argv or "--help" in sys.argv: _help() elif len(sys.argv) == 2: face_detect(sys.argv[1]) else: face_detect()