【问题标题】:Read all images from folder and detect faces, crop and save to new folder从文件夹中读取所有图像并检测人脸,裁剪并保存到新文件夹
【发布时间】:2019-05-29 22:19:01
【问题描述】:

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

当我收到错误时,谁能帮我写代码:

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()

【问题讨论】:

    标签: python opencv image-processing mat


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      试试这个

      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)
      

      【讨论】:

        猜你喜欢
        • 2011-11-14
        • 1970-01-01
        • 1970-01-01
        • 2021-10-20
        • 1970-01-01
        • 2021-08-31
        • 2012-11-12
        • 2016-10-28
        • 2016-02-11
        相关资源
        最近更新 更多