簡體   English   中英

人臉識別Python Open CV

[英]Face Recoginition Python open cv

有什么辦法可以讓我自己的火車在python中進行人臉識別嗎? 更具體地說,我想制作像AT&T Face數據庫這樣的火車。 我希望我的相機拍攝每個人20張圖像(最多30張),並按每個人的名字將其存儲在單獨的文件夾中。

import cv2, sys, numpy, os
size = 4
fn_haar = 'haarcascade_frontalface_default.xml'
fn_dir = 'att_faces'
fn_name = sys.argv[1]
path = os.path.join(fn_dir, fn_name)
if not os.path.isdir(path):
    os.mkdir(path)
(im_width, im_height) = (112, 92)
haar_cascade = cv2.CascadeClassifier(fn_haar)
webcam = cv2.VideoCapture(0)

# The program loops until it has 20 images of the face.
count = 0
while count < 20:
    (rval, im) = webcam.read()
    im = cv2.flip(im, 1, 0)
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    mini = cv2.resize(gray, (gray.shape[1] / size, gray.shape[0] / size))
    faces = haar_cascade.detectMultiScale(mini)
    faces = sorted(faces, key=lambda x: x[3])
    if faces:
        face_i = faces[0]
        (x, y, w, h) = [v * size for v in face_i]
        face = gray[y:y + h, x:x + w]
        face_resize = cv2.resize(face, (im_width, im_height))
        pin=sorted([int(n[:n.find('.')]) for n in os.listdir(path)
               if n[0]!='.' ]+[0])[-1] + 1
        cv2.imwrite('%s/%s.png' % (path, pin), face_resize)
        cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3)
        cv2.putText(im, fn_name, (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN,
            1,(0, 255, 0))
        count += 1
    cv2.imshow('OpenCV', im)
    key = cv2.waitKey(10)
    if key == 27:
        break

為此,您只需要提供一個特定路徑即可以排序方式保存所有擴展名為(.png)或(.bmp)或(.jpg)的圖像。

# train.py
import cv2, sys, numpy, os
size = 4
fn_haar = 'haarcascade_frontalface_default.xml'
fn_dir = 'face_data'

fn_name = sys.argv[0]


path = os.path.join(fn_dir, fn_name)

(im_width, im_height) = (112, 92)
haar_cascade = cv2.CascadeClassifier(fn_haar)
webcam = cv2.VideoCapture(0)

# Generate name for image file
pin=sorted([int(n[:n.find('.')]) for n in os.listdir(path)
 if n[0]!='.' ]+[0])[-1] + 1

# Beginning message
print("\n\033[94mThe program will save 20 samples. \
Move your head around to increase while it runs.\033[0m\n")

# The program loops until it has 20 images of the face.
count = 0
pause = 0
count_max = 20
while count < count_max:

  # Loop until the camera is working
  rval = False
  while(not rval):
    # Put the image from the webcam into 'frame'
    (rval, frame) = webcam.read()
    if(not rval):
        print("Failed to open webcam. Trying again...")

# Get image size
height, width, channels = frame.shape

# Flip frame
frame = cv2.flip(frame, 1, 0)

# Convert to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Scale down for speed
mini = cv2.resize(gray, (int(gray.shape[1] / size), int(gray.shape[0] / size)))

# Detect faces
faces = haar_cascade.detectMultiScale(mini)

# We only consider largest face
faces = sorted(faces, key=lambda x: x[3])
if faces:
    face_i = faces[0]
    (x, y, w, h) = [v * size for v in face_i]

    face = gray[y:y + h, x:x + w]
    face_resize = cv2.resize(face, (im_width, im_height))

    # Draw rectangle and write name
    cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
    cv2.putText(frame, fn_name, (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN,
        1,(0, 255, 0))

    # Remove false positives
    if(w * 6 < width or h * 6 < height):
        print("Face too small")
    else:

        # To create diversity, only save every fith detected image
        if(pause == 0):

            print("Saving training sample "+str(count+1)+"/"+str(count_max))

            # Save image file
            cv2.imwrite('%s/%s.png' % (path, pin), face_resize)

            pin += 1
            count += 1

            pause = 1

if(pause > 0):
    pause = (pause + 1) % 5
cv2.imshow('OpenCV', frame)
key = cv2.waitKey(10)
if key == 27:
    break

此代碼將幫助您從網絡攝像頭獲取裁剪的圖像,並將它們存儲在目錄名稱中作為face_data進行培訓。 如果您不想從網絡攝像頭訓練數據集,只需做一件事:只需創建一個目錄並在其中創建5-6個子目錄即可,例如Happy,Sad,Angry,Neutral,Calm等。下載圖像並將其放在相應的文件夾中以進行培訓,現在請遵循以下代碼。

## This program first ensures if the face of a person exists in the given image or 
not then if it exists, it crops
## the image of the face and saves to the given directory.

## Importing Modules
import cv2
import os


directory = "C:\\Users\\hp"

## directory where the images to be saved:
f_directory = "C:\\Users\\hp\\face_data/"

def facecrop(image):
   ## Crops the face of a person from an image!

   ## OpenCV XML FILE for Frontal Facial Detection using HAAR CASCADES.
   facedata=    
   "C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml"
   cascade = cv2.CascadeClassifier(facedata)

   ## Reading the given Image with OpenCV
   img = cv2.imread(image)

   try:    
    minisize = (img.shape[1],img.shape[0])
    miniframe = cv2.resize(img, minisize)

    faces = cascade.detectMultiScale(miniframe)

    for f in faces:
        x, y, w, h = [ v for v in f ]
        cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)

        sub_face = img[y:y+h, x:x+w]

        f_name = image.split('/')
        f_name = f_name[-1]

        ## Change here the Desired directory.
        cv2.imwrite(f_directory + f_name, sub_face)
        print ("Writing: " + image)

except:
    pass

if __name__ == '__main__':
    images = os.listdir(directory)
    i = 0

for img in images:
    file = directory + img
    print (i)
    facecrop(file)
    i += 1

暫無
暫無

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

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