python程序检测人脸并将其插入文件夹中

问题描述 投票:-2回答:1

我创建了一个python程序,该程序创建一个文件夹并从用户那里获取名称,然后从相机中检测到脸部并拍摄30张脸部图像。问题是我希望将照片保存在新创建的文件中,而代码仅将图像保存在给定的路径中,而不保存在新文件夹中。这是我正在处理的文件:

import os 
import cv2

cam = cv2.VideoCapture(0)
cam.set(3, 640) # set video width
cam.set(4, 480) # set video height

face_cascade = cv2.CascadeClassifier('data/haarcascade_frontalface_alt2.xml')

# Directory 
directory = input("\n enter user id end press <return> ==>  ")
#directory = "GeeksforGeeks"

# Parent Directory path 
parent_dir = "C:/Users/User/Desktop/images/"

# Path 
path = os.path.join(parent_dir, directory) 

# Create the directory 
new_path = os.mkdir(path) 
print("Directory '% s' created" % directory) 
print(path)


print("\n [INFO] Initializing face capture. Look the camera and wait ...")
# Initialize individual sampling face count
count = 0

while(True):
    ret, img = cam.read()
   # img = cv2.flip(img, -1) # flip video image vertically
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)

    for (x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
        count += 1

        # Save the captured image into the datasets folder
        cv2.imwrite(str(path) + str(directory) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])

        cv2.imshow('image', img)

    k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video
    if k == 27:
        break
    elif count >= 30: # Take 30 images sample and stop video
         break

# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
python image opencv directory face-detection
1个回答
1
投票

更改此行:

cv2.imwrite(str(path) + str(directory) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])

至此:

cv2.imwrite(str(path) + '/' + str(directory) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
© www.soinside.com 2019 - 2024. All rights reserved.