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

vqlkdk9b  于 2023-08-06  发布在  Python
关注(0)|答案(1)|浏览(97)

我已经创建了一个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()

字符串

rqenqsqc

rqenqsqc1#

更改此行:

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])

相关问题