【问题标题】:Saving faces openCV保存面孔openCV
【发布时间】:2018-10-02 09:01:13
【问题描述】:

我有一个裁剪面部的代码,我正在尝试保存裁剪后的图像。我的代码只保存一张图片。你能帮我扩展功能,以便程序将所有面孔保存到单独的文件中

import cv2
import os


def facecrop(image):
    facedata = "haarcascade_frontalface_alt.xml"
    cascade = cv2.CascadeClassifier(facedata)

    img = cv2.imread('class.jpg')

    minisize = (img.shape[1], img.shape[0])
    miniframe = cv2.resize(img, minisize)

    faces = cascade.detectMultiScale(miniframe)

    for f in faces:
        x, y, w, h = [v for v in f]
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255))

        sub_face = img[y:y + h, x:x + w]
        fname, ext = os.path.splitext(image)
        cv2.imwrite(fname + "_cropped_" + ext, sub_face)

    return

facecrop("1.jpg")

【问题讨论】:

  • 每张图片是否只有一张脸?如果不是,那么您的代码每张图像只保存一张脸,您必须为此更改他们的名称。

标签: python-3.x opencv face-detection


【解决方案1】:

您只需要有一个计数器并将其添加到您的文件名中。发生的事情是,您正在用相同的文件名覆盖图像。因此,您只得到一张图像。下面是代码sn-p

import cv2
import os


def facecrop(image):
    facedata = "haarcascade_frontalface_alt.xml"
    cascade = cv2.CascadeClassifier(facedata)

    img = cv2.imread('class.jpg')

    minisize = (img.shape[1], img.shape[0])
    miniframe = cv2.resize(img, minisize)

    faces = cascade.detectMultiScale(miniframe)
    counter = 1

    for f in faces:
        x, y, w, h = [v for v in f]
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255))

        sub_face = img[y:y + h, x:x + w]
        fname, ext = os.path.splitext(image)
        cv2.imwrite(fname + "_cropped_" + str(counter) + ext, sub_face)
        counter = counter + 1

    return

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 1970-01-01
    • 2012-12-28
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    相关资源
    最近更新 更多