如何自动选择和处理/ root / facedetect目录中的每个图像,而不是选择特定图像

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

如果可以这样做,有没有办法在一个单独的目录中自动发送所有检测到面部的图像,或者压缩它们?

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('/root/opencv/modules/objdetect/src/haarcascade_frontalface_alt.xml')

img = cv2.imread('/root/facedetect/1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
python python-3.x python-2.7
2个回答
1
投票

从任何地方运行此脚本(在这种情况下,os模块很有用):

import os
import numpy as np
import cv2

path = `root/facedetect`  # Set your path, where are images exists
files = os.listdir(path)  # Get all the files in that directory
print("Files in '%s': %s" % (path, files))
# Remain only files with specified type
files = [f for f in files if ".jpg" in f or ".jpeg" in f]
# Create directory if not exists:
newpath = path + "/recognized"
if not os.path.exists(newpath):
    os.makedirs(newpath)
# Specify classifier:
face_cascade = cv2.CascadeClassifier('/root/opencv/modules/objdetect/src/haarcascade_frontalface_alt.xml')
# Loop over each and save in a new directory
for i in files:
    # Path to image
    img = cv2.imread(os.path.join(path, i))
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    # Proceed if detect at least one face
    if faces != ():
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = img[y:y+h, x:x+w]
        cv2.imwrite(os.path.join(newpath, i), img)
print("Done")

1
投票

您可以使用os模块获取文件夹中的所有图像。 然后使用shutil模块将一些图像复制到另一个文件夹中。

    import osimage_path
    from shutil import copyfile

    images_folder = '/root/facedetect'
    images = os.listdir(images_folder)

    detected_faces_folder = '/root/detected_faces'

    for image in images:
        image_path = os.path.join(images_folder, image)
        img = cv2.imread(image_path)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        ...
        ...

        if detected_faces:
            copyfile(image_path, os.path.join(detected_faces_folder, image))
© www.soinside.com 2019 - 2024. All rights reserved.