【问题标题】:python program detect faces and insert them in a folderpython程序检测面部并将它们插入文件夹中
【发布时间】:2020-06-17 17:20:35
【问题描述】:

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

【问题讨论】:

  • 你的措辞有点混乱。您说“给定路径中的图像不在新文件夹中”,但没有明确指出两者之间的区别。读者可以通过阅读您的代码 sn-p 来解决这个问题,但如果您明确说明代码做错了什么(更不用说它也可以帮助您排除故障),这会让所有人都更容易。

标签: python image opencv directory face-detection


【解决方案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])

【讨论】:

  • 非常感谢代码现在可以正常工作,并将图像保存在新文件夹中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2021-02-16
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多