python - 循环浏览目录并将所有面孔保存在其他目录中

标签 python opencv

我想遍历目录中的所有图像并将面部保存在其他目录中。这是我的代码。

cascPath = "haarcascade_frontalface_alt2.xml"

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

import glob
files=glob.glob("*.jpg")
for file in files:

    # Read the image
    image = cv2.imread(file)
    print(file)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Detect faces in the image
    faces = faceCascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=4,
        minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE)
    print ("Found {0} faces!".format(len(faces)))

    # Crop Padding
    left = 10
    right = 10
    top = 10
    bottom = 10

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        print (x, y, w, h)

        image  = image[y-top:y+h+bottom, x-left:x+w+right]

        print ("cropped_{1}{0}".format(str(file),str(x)))
        cv2.imwrite("cropped_{1}_{0}".format(str(file),str(x)), image)

上面的代码期望图像为jpg格式。它还从根文件夹检索图像,并将其保存在根文件夹本身中。
如何遍历test_input目录并将所有面孔保存在test_output目录中?

最佳答案

要遍历test_input,请修改传递给glob.glob的字符串:

files = glob.glob("test_input/*.jpg")

要保存到特定的输出目录,只需在保存图像时指定该目录。使用os.path.join安全地连接路径。
import os
cv2.imwrite(os.path.join("test_output", "cropped_{1}_{0}".format(str(file),str(x))), image)

关于python - 循环浏览目录并将所有面孔保存在其他目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474133/

相关文章:

python - 使用子进程调用从 python 函数重新启动 Linux 服务器

OpenCV 从网络摄像头绘制具有 2 个最大对象的矩形

python - 如何在完全透明的物体中找到矩形?

c++ - MacOS 上的视频捕获

python - 安排任务每 n 秒运行一次,从特定时间开始

python - 引用类变量而不在 Python 中创建实例

python - 为什么 raise_for_status() 没有发现错误?

python-3.x - 如何在python中使用opencv-python将RGB888转换为RGB565?

opencv - 傅立叶图像的翻译

python 3 正则表达式 : match a character exactly once