【问题标题】:How to fix "“TypeError: img should be PIL Image. Got <class ‘str’>”?如何修复““TypeError:img应该是PIL Image。得到<class'str'>”?
【发布时间】:2019-07-04 06:22:09
【问题描述】:

我是初学者,我正在学习编写图像分类器。我的目标是创建一个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')

【问题讨论】:

  • 报错说image是字符串,所以不要传字符串,传PIL图片
  • 请加你process_image()
  • @DeveshKumarSingh 我不熟悉通过 PIL。你想展示一个如何传递字符串的例子吗?

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


【解决方案1】:

由于predict 函数中的以下行,您会收到上述错误:

img = process_image(image)

process_image 函数的输入应该是 Image.open(image),而不是 image,它基本上是图像(字符串)的路径,因此是错误消息 TypeError: img should be PIL Image. Got &lt;class ‘str’&gt;

所以,将img = process_image(image) 更改为img = process_image(Image.open(image))

修改predict函数:

def predict(image, model, topk=5):
    ''' 
      Predict the class (or classes) of an image using a trained deep learning model.
      Here, image is the path to an image file, but input to process_image should be                                                         
      Image.open(image)
    '''
    img = process_image(Image.open(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

【讨论】:

猜你喜欢
  • 2021-01-26
  • 2021-06-24
  • 2020-11-05
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2021-07-16
  • 1970-01-01
相关资源
最近更新 更多