为什么我得到 AttributeError?

Why did I get AttributeError?

我尝试更改原始代码中的几行,但是当我尝试 运行 时,我收到错误提示“AttributeError:模块 'PngImageFile' 没有属性 'shape'。 但是,当 运行ning 原始代码时,我没有问题。我应该怎么做才能消除修改后的代码中的这个错误?

原代码如下:

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

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

img = np.asarry(img)

编辑:

还有其他问题。

anna_phog 转换颜色 BGR2GRAY 因为 cv2BGR 中给出颜色而不是 RGB - 但是 pillow 在 [=] 中给出颜色20=]。所以最好使用 cv2 来读取图像。