当前位置: 首页 > 面试题库 >

Python OpenCV人脸检测代码有时会引发'tuple'对象没有属性'shape'`

柳项明
2023-03-14
问题内容

我正在尝试使用opencv在python中构建人脸检测应用程序。
请参阅下面的代码段:

 # Loading the Haar Cascade Classifier
cascadePath = "/home/work/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)

# Dictionary to store image name & number of face detected in it
num_faces_dict = {}

# Iterate over image directory. 
# Read the image, convert it in grayscale, detect faces using HaarCascade Classifier
# Draw a rectangle on the image

for img_fname in os.listdir('/home/work/images/caltech_face_dataset/'):
    img_path = '/home/work/images/caltech_face_dataset/' + img_fname
    im = imread(img_path)
    gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
    faces = faceCascade.detectMultiScale(im)
    print "Number of faces found in-> ", img_fname, " are ", faces.shape[0]
    num_faces_dict[img_fname] = faces.shape[0]
    for (x,y,w,h) in faces:
        cv2.rectangle(im, (x,y), (x+w,y+h), (255,255,255), 3)
    rect_img_path = '/home/work/face_detected/rect_' + img_fname
    cv2.imwrite(rect_img_path,im)

此代码对于大多数图像都适用,但是对于其中的某些图像则会引发错误-

AttributeError:“元组”对象没有属性“ shape”
在此处输入图片说明

在打印面数的行中出现错误。任何帮助,将不胜感激。


问题答案:

问题的原因是当没有匹配项时detectMultiScale返回一个空的元组(),而numpy.ndarray在有匹配项时返回一个空的元组。

>>> faces = classifier.detectMultiScale(cv2.imread('face.jpg'))
>>> print(type(faces), faces)
<class 'numpy.ndarray'> [[ 30 150  40  40]]

>>> faces = classifier.detectMultiScale(cv2.imread('wall.jpg'))
>>> print(type(faces), faces)
<class 'tuple'> ()

您可能期望负结果将是形状为(0,4)的ndarray,但事实并非如此。

该行为及其背后的原因未在文档中进行说明,而是指示返回值应为“对象”。

OpenCV有很多这样的疣,而隐秘的错误消息也无济于事。处理它的一种方法是在代码中添加日志记录语句或断言,以检查所有内容是否都是您期望的类型。

探索库如何在诸如 ipython之类 的repl中工作是非常有用的。这在Rahul
KP的答案中使用

在这种情况下,您可以不使用来解决您的问题shape。Python有那些序列或集合,例如许多的数据类型tuplelistdict。所有这些都实现了len()内置功能,您也可以使用循环它们for x in y。相反,shape它只是的一个属性numpy.ndarray,在任何内置的python数据类型中都找不到。

如果您将代码重写为uselen(faces)而不是,则您的代码应该可以工作faces.shape[0],因为前者可同时用于tuple和ndarray。

for img_fname in os.listdir('/home/work/images/caltech_face_dataset/'):
    img_path = '/home/work/images/caltech_face_dataset/' + img_fname
    im = imread(img_path)
    gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
    faces = faceCascade.detectMultiScale(gray)  # use the grayscale image
    print "Number of faces found in-> {} are {}".format(
        img_fname, len(faces))  # len() works with both tuple and ndarray
    num_faces_dict[img_fname] = len(faces)
    # when faces is (), the following loop will never run, so it's safe.
    for (x,y,w,h) in faces: 
        cv2.rectangle(im, (x,y), (x+w,y+h), (255,255,255), 3)
    rect_img_path = '/home/work/face_detected/rect_' + img_fname
    cv2.imwrite(rect_img_path,im)


 类似资料:
  • 这是我的密码: 这条线给了我错误 "属性错误:'浮点'对象没有属性'exp'"。X,t是Numpy ndarray。

  • 我试图建立一个用户登录系统,我已经成功地建立了用户注册页面,但是当我试图登录时,我得到了下面的错误。我使用烧瓶,python3.6和pymongo。这是一个错误:请帮助。 Traceback(最近一次调用最后一次):文件"C:\用户\elvis\AppData\本地\程序\Python\Python36\lib\site-包\flask\app.py",第2309行,在调用返回self.wsgi_

  • 1.接口描述 对照片中的人脸进行检测,返回人脸数目和每张人脸的位置信息 图片要求 格式为 JPG(JPEG),BMP,PNG,GIF,TIFF 宽和高大于 8px,小于等于4000px 小于等于 5 MB 请求方式: POST 请求URL: https://cloudapi.linkface.cn/face/face_detect 2.请求参数 字段 类型 必需 描述 api_id string

  • 问题内容: 我正在开发Django应用程序,并且出现以下错误 我的模型是这样构造的 我应该做什么? 问题答案: 首先,您必须非常小心地重写以具有非可选参数。记住,每次从一个查询集中获取一个对象时,它将被调用! 这是您想要的正确代码: 如果您只使用该对象的子类,我强烈建议在Animal上设置abstract选项。这样可以确保不为动物创建表,而仅为绵羊(等)创建表。如果未设置abstract,则将创建

  • 我创建了这个简单的GUI: 我让用户界面启动并运行。当我点击按钮时,我在控制台上得到以下错误: 为什么设置为?

  • 使用Python 2.7,我使用Tkinter构建了一个图形用户界面。在我的图形用户界面上,我有一个打开输入弹出框的按钮。对弹出框的调用是: 弹出框构造为: 在弹出框中输入任何内容之前,我得到一个错误;完整堆栈跟踪如图所示(分为几行,因此它不仅仅是一堆文本): Tkinter回调中的异常 回溯(最近一次呼叫最后一次): 文件“C:\用户\ajpung\AppData\本地\连续体\Anaconda