【问题标题】:Why did I get AttributeError?为什么我得到 AttributeError?
【发布时间】:2021-08-27 23:50:39
【问题描述】:

我尝试从原始代码中更改几行,但是当我尝试运行时,我收到错误消息,提示“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, bin, angle, Level, roi)# fd= feature descriptor
     11         data.append(p)
     12         labels.append(count)

~\Desktop\FYP\anna_phog.ipynb in anna_phog(Img, bin, angle, 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, bin, angle, Level, roi) #MODIFIED
     11             data.append(p)
     12             labels.append(count)

~\Desktop\FYP\anna_phog.ipynb in anna_phog(Img, bin, angle, L, 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, angle, bin)
     56     "    p = anna_PhogDescriptor(bh_roi,bv_roi,L,bin)\n",
     57     "    return p"
---> 58    ]
     59   },
     60   {

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

​

【问题讨论】:

  • anna_phog(img, bin, angle, Level, roi)替换anna_phog(Image, bin, angle, Level, roi)
  • @enzo 我试图更改该行,但是我仍然遇到属性错误,但现在它说'PngImageFile'没有属性'shape'。
  • 然后尝试用anna_phog(asarray(img), bin, angle, Level, roi)替换anna_phog(img, bin, angle, Level, roi)
  • 错误显示函数 anna_phog 内部的问题,但我没有看到此函数的代码。它似乎在某个文件 .ipynb 中 - 可能将其保存为正常 .py 或将所有 anna_phog 复制到此代码
  • .shape 可以建议您使用numpy array 但您使用pillow 加载图像Image.open() 可能需要转换为numpy array 才能使用.shape - np.asarray(img) .或者使用cv2.imread(...)而不是Image.open(),你会直接得到numpy array(但它需要将颜色BGR转换为RGB

标签: python attributeerror feature-extraction


【解决方案1】:

我在其他门户看到anna_phog

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

img = np.asarry(img)

编辑:

会有其他问题。

anna_phog 转换颜色 BGR2GRAY 因为cv2BGR 而不是 RGB 中提供颜色 - 但 pillowRGB 中提供颜色。所以最好使用cv2来读取图片。

【讨论】:

  • 谢谢,我已经将img = Image.open这一行改为img=cv2.imread,不再出现属性错误。但是,现在我仍然收到另一个错误说 TypeError: unsupported operand type(s) for /: 'int' and 'builtin_function_or_method'。
  • this ipynb 只会造成问题 - 它没有准确显示此错误在哪里。正常.py 应该显示与/ 一致。它在anna_BinMatrix 中显示问题,我看到.../bin 并且有内置函数bin() 并且通常代码2/bin 会产生与您得到的相同的错误。所以问题可能是你的代码中的变量bin - 你没有bin = ...,它使用内置的bin()。你必须决定你需要分配什么bin =...,因为我不知道它应该是什么。
猜你喜欢
  • 1970-01-01
  • 2017-10-26
  • 2022-11-14
  • 2021-08-24
  • 2017-11-18
  • 2019-09-29
相关资源
最近更新 更多