类型错误:“图像”对象不支持项目分配

Bro*_*983 2 python opencv pytorch

我正在运行下面的模型,在分割图像并尝试将图像分配回来后,我收到错误消息。

    sample[:, :, 0] = 0
TypeError: 'Image' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的方法将图像分配回样本,但这没有帮助。任何帮助将不胜感激。非常感谢

这是我用来加载数据的代码:

import os

import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms, utils
from torchvision.transforms import functional
#from torchvision.transforms import Grayscalei
import pandas as pd
import pdb
import cv2
from cv2 import imread
from cv2 import resize

class CellsDataset(Dataset):
    # a very simple dataset

    def __init__(self, root_dir, transform=None, return_filenames=False):
        self.root = root_dir
        self.transform = transform
        self.return_filenames = return_filenames
        self.files = [os.path.join(self.root,filename) for filename in os.listdir(self.root)]
        self.files = [path for path in self.files
                      if os.path.isfile(path) and os.path.splitext(path)[1]=='.png']

    def __len__(self):
        return len(self.files)

        path = self.files[idx]
        sample = Image.open(path)
        sample = np.asarray(sample, dtype=np.uint8)
        sample = cv2.resize(src=sample, dsize=(1024, 1024))
        sample = functional.to_grayscale(sample, num_output_channels=3)

        sample[:, :, 0] = 0
        sample[:, :, 1] = 0

        if self.transform:
            sample = self.transform(sample)

        if self.return_filenames:
            return sample, path
        else:
            return sample

    def duplicate_and_transform(self,transforms):
        currfilelen = self.__len__()
        
        for pind in range(0,currfilelen-1):
            path = self.files[pind]
            sample = Image.open(path)
            samplet = transforms(sample)
            # save the transformed images and save the associated counts:
            newpath = path[:-4]+'trans.png' #path[:-4] is the path without the .png extension.
            samplet.save(newpath,"PNG")
            metadata = pd.read_csv(os.path.join(self.root,'gt_red.csv'))
            metadata.set_index('filename',inplace=True)
            count = metadata['count'][os.path.split(path)[-1]]
            samplet.save(newpath,"PNG")
            f = open(self.root+'gt.csv','a')
            basepath = os.path.basename(path) # strip away the directory list and just get the filename
            f.write(basepath[:-4]+'trans.png,'+str(count)+'\n')
            # return the new file names and add to self.files.
            self.files.append(newpath)
            #pdb.set_trace()
Run Code Online (Sandbox Code Playgroud)

小智 6

您直接操作 PIL 对象。您必须首先将其转换为 numpy 数组,然后操作这些值:

sample = Image.open(path)
sample = np.asarray(sample, dtype=np.uint8)
Run Code Online (Sandbox Code Playgroud)