从文件夹中读取所有图像并检测人脸,裁剪并保存到新文件夹



我正在尝试构建一个模型,在该模型中,它将读取给定文件夹中的所有图像并检测面部,裁剪并将裁剪后的面部保存到新文件夹中!

当我收到错误时,任何人都可以帮助我编写代码:

cv2.imshow(str(img) , img)
TypeError: mat is not a numpy array, neither a scalar

法典:

import glob 
import cv2
import sys
while 1 :
    filename = input("Enter the file name in which images are present =")
    for img in glob.glob(filename+'/*.*'):
        #try :
            var_img = cv2.imread(img)
            cv2.imshow(str(img) , var_img)
    def detect_face(img):
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        face_cascade = cv2.CascadeClassifier('opencv-files/lbpcascade_frontalface.xml')
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
        if (len(faces) == 0):
            return None, None
        (x, y, w, h) = faces[0]
        return gray[y:y+w, x:x+h], faces[0]
    cv2.imshow(str(img) , img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

看起来您正在尝试显示文件名而不是实际数组。 glob.glob返回文件名列表,因此您尝试显示的img只是一个字符串。在显示图像之前,您需要先阅读图像。您在此行中执行此操作:var_img = cv2.imread(img),这意味着您的数组var_img 。但后来你试图再次显示只用img.您只能显示var_img哪个是数组,而不能显示哪个是字符串img

试试这个

import glob 
import cv2
import sys
import os
def detect_face(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    face_cascade = cv2.CascadeClassifier('opencvfiles/lbpcascade_frontalface.xmlv')
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
    return faces
filename = input("Enter the file name in which images are present =")
for img in glob.glob(filename+'/*.*'):
    var_img = cv2.imread(img)
    face = detect_face(var_img)
    print(face)
    if (len(face) == 0):
        continue
    for(ex, ey, ew, eh) in face:
        crop_image = var_img[ey:ey+eh, ex:ex+ew]
        cv2.imshow("cropped", crop_image)
        cv2.waitKey(0)  
    cv2.imwrite(os.path.join("outputs/",str(img)),crop_image)

相关内容

  • 没有找到相关文章

最新更新