gpt4 book ai didi

python - TypeError:图片应为PIL图像或ndarray。得到了

转载 作者:行者123 更新时间:2023-12-02 17:19:25 26 4
gpt4 key购买 nike

我想使用Open CV拆分图像,然后将其馈送到PyTorch模型以计算每个图像中的对象。运行代码时出现以下错误消息:TypeError:图片应为PIL图像或ndarray。有

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 Grayscalei
import pandas as pd
import pdb
import cv2

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)

def __getitem__(self, idx):
path = self.files[idx]
sample = Image.open(path)

sample = cv2.imread(path)
b,g,r=cv2.split(sample)
sample=cv2.imwrite('sample.png', g)


#transform3 = Grayscale(num_output_channels=3)
#sample = transform3(sample) # convert to a 3 channel grayscale, as it needs to be 3 channel.
if self.transform:
sample = self.transform(sample)

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

最佳答案

变量sample被重新分配给此行中cv2.imwrite返回的内容:

sample=cv2.imwrite('sample.png', g)
那用其他东西代替了你的ndarray。
尝试用简单的 cv2.imwrite('sample.png', g)替换该行,而不将评估表达式的值分配给 sample

关于python - TypeError:图片应为PIL图像或ndarray。得到了<class ‘bool’>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62924547/

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