为什么我会收到 AttributeError?

如何解决为什么我会收到 AttributeError?

我尝试更改原始代码中的几行,但是当我尝试运行时,出现错误提示“AttributeError: module 'PngImageFile' has no attribute 'shape'。 但是,我在运行原始代码时没有问题。我应该怎么做才能消除修改后的代码中的这个错误

这是原始代码

from skimage.feature import hog,local_binary_pattern
from skimage.transform import pyramid_gaussian
from skimage.io import imread
import joblib
from sklearn.preprocessing import LabelEncoder
from sklearn import svm
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from skimage import color
from imutils.object_detection import non_max_suppression
import imutils
import numpy as np
import argparse
import cv2
import os
import glob
from sklearn import metrics
from PIL import Image # This will be used to read/modify images (can be done via OpenCV too)
from numpy import *

# define parameters of HOG feature extraction
orientations = 9
pixels_per_cell = (8,8)
cells_per_block = (2,2)
threshold = .3

# define path to images:
dataset_path = r"C:\Users\user\Documents\FYP\Dataset FYP\Train New\Contrast" # path of our dataset
    
# compute HOG features and label them:

for category in category_im_listing: #this loop enables reading the files in the pos_im_listing variable one by one
    im_listing = os.listdir(dataset_path + "/" + category)
    num_im = size(im_listing)
    print("There are " + str(num_im) + " images in category " + str(count + 1))
    for file in im_listing:
        img = Image.open(dataset_path + "/" + category + "/" + file) # open the file
        img = img.resize((150,150))
        gray = img.convert('L') # convert the image into single channel i.e. RGB to grayscale
        # calculate HOG for positive features
        fd = hog(gray,orientations,pixels_per_cell,cells_per_block,block_norm='L2',feature_vector=True)# fd= feature descriptor
        data.append(fd)
        labels.append(count)
    count = count + 1

这是我修改后出错的代码

    from skimage.feature import hog,local_binary_pattern
    from skimage.transform import pyramid_gaussian
    from skimage.io import imread
    import joblib
    from sklearn.preprocessing import LabelEncoder
    from sklearn import svm
    from sklearn.metrics import classification_report
    from sklearn.model_selection import train_test_split
    from skimage import color
    from imutils.object_detection import non_max_suppression
    import imutils
    import numpy as np
    import imageio
    from ipynb.fs.full.anna_phog import anna_phog
    import argparse
    import cv2
    import os
    import glob
    from sklearn import metrics
    from PIL import Image # This will be used to read/modify images (can be done via OpenCV too)
    from numpy import *
    
    image_path = r"C:\Users\user\Documents\FYP\me\train"
    
    #MODIFIED
    S = 8
    angle = 360
    Level = 3
    roi = [1,225,1,300]
    save=True
    
    # read the image files:
    category_im_listing = os.listdir(image_path) # it will read all the files in the path
    num_category_im = size(category_im_listing) # simply states the total no. of category
    print("There are " + str(num_category_im) + " categories") # prints the number value of the no.of categories dataset
    data= []
    labels = []
    count = 0
    
    # Modified : I deleted the resize and gray line,and change the fd line into p because I want to extract PHOG instead of HOG
    for category in category_im_listing: #this loop enables reading the files in the pos_im_listing variable one by one
        im_listing = os.listdir(image_path + "/" + category)
        num_im = size(im_listing)
        print("There are " + str(num_im) + " images in category " + str(count + 1))
        for file in im_listing:
            img = Image.open(image_path + "/" + category + "/" + file) # open the file
            # calculate PHOG for positive features
            p = anna_phog(img,bin,angle,Level,roi) #MODIFIED
            data.append(p)
            labels.append(count)
        count = count + 1

这是我在修改后的代码中得到的错误

    ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-76-9e9360ca5082> in <module>
      8         img = Image.open(image_path + "/" + category + "/" + file) # open the file
      9         # calculate HOG for positive features
---> 10         p = anna_phog(img,roi)# fd= feature descriptor
     11         data.append(p)
     12         labels.append(count)

~\Desktop\FYP\anna_phog.ipynb in anna_phog(Img,L,roi)
     11     "import cv2\n",12     "import matplotlib.pyplot as plt"
---> 13    ]
     14   },15   {

AttributeError: 'PngImageFile' object has no attribute 'shape'

错误(更新):

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-00f72c361b79> in <module>
      8             img=cv2.imread(image_path + "/" + category + "/" + file) # open the file
      9             # calculate PHOG for positive features
---> 10             p = anna_phog(img,roi) #MODIFIED
     11             data.append(p)
     12             labels.append(count)

~\Desktop\FYP\anna_phog.ipynb in anna_phog(Img,roi)
     35     "        E = cv2.Canny(G,lower,upper) #high and low treshold\n",36     "        GradientX,GradientY = np.gradient(G)\n",---> 37     "        GradientYY = np.gradient(GradientY,axis=1)\n",38     "        \n",39     "        Gr = np.sqrt(np.square(GradientX)+np.square(GradientY))\n",~\Desktop\FYP\anna_phog.ipynb in anna_BinMatrix(A,E,G,bin)
     56     "    p = anna_PhogDescriptor(bh_roi,bv_roi,bin)\n",57     "    return p"
---> 58    ]
     59   },60   {

TypeError: unsupported operand type(s) for /: 'int' and 'builtin_function_or_method'

​

解决方法

我在其他门户网站上看到了 anna_phog

问题是因为这个函数需要 numpy array 但是你用 pillow Image.open() 读取图像并且你必须将 img 转换为 numpy array

img = np.asarry(img)

编辑:

会有其他问题。

anna_phog 转换颜色 BGR2GRAY 因为 cv2BGR 中给出颜色而不是 RGB - 但 pillow 在 {{1} 中给出颜色}.所以最好使用 RGB 来读取图像。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?