我有一个裁剪面孔的代码,我正在尝试保存裁剪的图像。我的代码只保存一个图像。你可以帮我扩展功能,以便程序将所有面孔保存到单独的文件中
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”)
答案 0 :(得分:2)
您只需要一个计数器并将其添加到您的文件名中。发生了什么,你用相同的文件名覆盖图像。因此,您只获得一个图像。以下是代码段
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
希望它有所帮助!