簡體   English   中英

Python + OpenCV:cv2.imwrite

[英]Python+OpenCV: cv2.imwrite

我正在嘗試檢測一張臉並在一個單獨的文件中記下臉部區域。 我該怎么做? 我認為我必須使用“faces”(你可以在代碼中看到這個var)。 但是怎么樣?

from ffnet import mlgraph, ffnet, tmlgraph, imlgraph
import pylab
import sys
import cv,cv2
import numpy
cascade = cv.Load('C:\opencv\data\haarcascades\haarcascade_frontalface_alt.xml')


def detect(image):
 bitmap = cv.fromarray(image)
 faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
 if faces:
  for (x,y,w,h),n in faces:  
   cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
 return image

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        frame = numpy.asarray(detect(frame))
        cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

以下代碼應提取圖像中的面部並將面部保存在磁盤上

def detect(image):
    image_faces = []
    bitmap = cv.fromarray(image)
    faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
    if faces:
        for (x,y,w,h),n in faces:
            image_faces.append(image[y:(y+h), x:(x+w)])
            #cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
    return image_faces

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        image_faces = []
        image_faces = detect(frame)
        for i, face in enumerate(image_faces):
            cv2.imwrite("face-" + str(i) + ".jpg", face)

        #cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

在此輸入圖像描述 在此輸入圖像描述 在此輸入圖像描述

或者 ,使用MTCNN和OpenCV(還需要包括TensorFlow在內的其他依賴項),您可以:

1 執行面部檢測 (輸入圖像,輸出檢測到的所有面部框):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box':[73,69,98,123],'confidence':0.9996458292007446,'keypoints':{'left_eye':( 102,116),'right_eye':( 150,114),'nose' :(129,142),'mouth_left':( 112,168),'mouth_right':( 146,167)}}]

2 將所有檢測到的面部保存到單獨的文件

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3或繪制所有檢測到的面的矩形

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

wtluo,太棒了! 我可以建議稍微修改你的代碼2.? 這里是:

for i, detected_box in enumerate(detect_boxes):
    box = detected_box["box"]
    face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM