gpt4 book ai didi

python - 类型错误 : 'Image' object does not support item assignment

转载 作者:行者123 更新时间:2023-12-02 16:50:40 25 4
gpt4 key购买 nike

我正在运行下面的模型,在拆分图像并尝试重新分配图像后,我收到了错误消息。

    sample[:, :, 0] = 0
TypeError: 'Image' object does not support item assignment

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

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

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()

最佳答案

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

sample = Image.open(path)
sample = np.asarray(sample, dtype=np.uint8)

关于python - 类型错误 : 'Image' object does not support item assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63307053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com