首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >人脸识别Python open cv

人脸识别Python open cv
EN

Stack Overflow用户
提问于 2016-09-26 14:31:57
回答 1查看 425关注 0票数 0

有没有办法用python制作我自己的人脸识别训练集?更具体地说,我想做一个像AT&T人脸数据库一样的训练集。我想让我的相机为每个人拍摄20张照片(最多30张),并按每个人的名字将其存储在单独的文件夹中。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2019-03-01 04:21:51

为此,您只需要提供一个特定的路径,以排序的方式保存带有(.png)或(.bmp)或(.jpg)扩展名的所有图像。

代码语言:javascript
复制
# 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等。下载图像并将它们放在相应的文件夹中用于训练目的,现在遵循以下代码。

代码语言:javascript
复制
## 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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39696061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档