如何解决““ TypeError:img应该是PIL图像。得到了<class'str'>” ??

时间:2019-07-03 17:58:21

标签: python deep-learning python-imaging-library pytorch

我是一个初学者,正在学习编码图像分类器。我的目标是创建一个predict函数。

是否有解决建议?

在这个项目中,我想使用预测功能来识别不同的花卉种类。所以我以后可以检查他们的标签。

试图修复:我已经使用了unsqueeze_(0)方法,并从numpy更改为torch方法。我通常会收到以下相同的错误消息:

  

TypeError:img应该是PIL

代码:


    # Imports here
    import pandas as pd
    import numpy as np

    import torch
    from torch import nn
    from torchvision import datasets, transforms, models
    import torchvision.models as models
    import torch.nn.functional as F
    import torchvision.transforms.functional as F
    from torch import optim
    import json

    from collections import OrderedDict
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    %matplotlib inline
    from PIL import Image

    def process_image(image):
     #Scales, crops, and normalizes a PIL image for a PyTorch model,
            #returns an Numpy array
        # Process a PIL image for use in a PyTorch model
        process = transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], 
                                 std=[0.229, 0.224, 0.225])
        ])
        image = process(image)
        return image

    # Predict 
    #Predict the class (or classes) of an image using a trained deep learning model.
    def predict(image, model, topk=5):

        img = process_image(image)
        img = img.unsqueeze(0)

        output = model.forward(img)
        probs, labels = torch.topk(output, topk)        
        probs = probs.exp()

        # Reverse the dict
        idx_to_class = {val: key for key, val in model.class_to_idx.items()}
        # Get the correct indices
        top_classes = [idx_to_class[each] for each in classes]

        return labels, probs

    #Passing 
    probs, classes = predict(image, model)
    print(probs)
    print(classes)

错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-92-b49fdcab5791> in <module>()
----> 1 probs, classes = predict(image, model)
     2 print(probs)
     3 print(classes)

<ipython-input-91-05809355bfe0> in predict(image, model, topk)
     2     ‘’' Predict the class (or classes) of an image using a trained deep learning model.
     3     ‘’'
----> 4     img = process_image(image)
     5     img = img.unsqueeze(0)
     6

<ipython-input-20-02663a696e34> in process_image(image)
    11                              std=[0.229, 0.224, 0.225])
    12     ])
---> 13     image = process(image)
    14     return image

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/transforms.py in __call__(self, img)
    47     def __call__(self, img):
    48         for t in self.transforms:
---> 49             img = t(img)
    50         return img
    51

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/transforms.py in __call__(self, img)
   173             PIL Image: Rescaled image.
   174         “”"
--> 175         return F.resize(img, self.size, self.interpolation)
   176
   177     def __repr__(self):

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/functional.py in resize(img, size, interpolation)
   187     “”"
   188     if not _is_pil_image(img):
--> 189         raise TypeError(‘img should be PIL Image. Got {}’.format(type(img)))
   190     if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)):
   191         raise TypeError(‘Got inappropriate size arg: {}’.format(size))

TypeError: img should be PIL Image. Got <class ‘str’>

我要做的就是得到这些相似的结果。谢谢!

    predict(image,model)
    print(probs)
    print(classes)
    tensor([[ 0.5607,  0.3446,  0.0552,  0.0227,  0.0054]], device='cuda:0')   
    tensor([[  8,   1,  31,  24,   7]], device='cuda:0')

1 个答案:

答案 0 :(得分:0)

由于stdout函数中的以下行,您遇到了以上错误:

predict

img = process_image(image) 函数的输入应该是process_image,而不是Image.open(image),它基本上是图像(字符串)的路径,因此是错误消息image。 / p>

因此,将TypeError: img should be PIL Image. Got <class ‘str’>更改为img = process_image(image)

修改后的img = process_image(Image.open(image))函数:

predict