Python用opencv提取照片上多個人臉
阿新 • • 發佈:2020-10-20
上程式碼:
import cv2 filepath = "imagePath/2.jpg" img = cv2.imread(filepath) # 讀取圖片 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 轉換灰色 # OpenCV人臉識別分類器 classifier = cv2.CascadeClassifier( "opencv-master\data\haarcascades\haarcascade_frontalface_default.xml" ) color = (0, 255, 0) # 定義繪製顏色 # 呼叫識別人臉faceRects = classifier.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32)) if len(faceRects): # 大於0則檢測到人臉 g = 0 for faceRect in faceRects: # 單獨框出每一張人臉 x, y, w, h = faceRect # 框出人臉 cv2.rectangle(img, (x, y), (x + h, y + w), color, 2) cropped= img[y:y+w, x:x+h] # 裁剪座標為[y0:y1, x0:x1] g = g + 1 cv2.imwrite("imagePath/2-%d.png" % g, cropped) ''' # 左眼 cv2.circle(img, (x + w // 4, y + h // 4 + 30), min(w // 8, h // 8), color) #右眼 cv2.circle(img, (x + 3 * w // 4, y + h // 4 + 30), min(w // 8, h // 8), color) #嘴巴 cv2.rectangle(img, (x + 3 * w // 8, y + 3 * h // 4), (x + 5 * w // 8, y + 7 * h // 8), color)''' ''' cv2.imshow("image", cropped) # 顯示影象 k = cv2.waitKey(0) if k == ord("s"): cv2.imwrite("imagePath/9-3.png", cropped) ''' cv2.destroyAllWindows()
效果:
原圖: