如何读取所有图像的形状并通过googlecolab显示在数据集文件夹中?

2024-09-30 12:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在googlecolab上训练我的图像数据集。我在colab中有数据集文件夹。当尝试从colab中的目录中读取图像时,我只能读取所有图像的文件名。但是,如果我尝试在一个数组中提取图像的形状,它会以不同的方法给出不同的错误。我试过使用os库和像素图像甚至泡菜,但我仍然无法排序,甚至猜不出可能是什么问题。

我遇到的错误有:

1) AttributeError: 'list' object has no attribute 'read'
2) AttributeError: 'list' object has no attribute 'seek'

在for循环中使用os.walk(path)函数和从路径中所有文件的结果列表中提取文件时。你知道吗

3) FileNotFoundError: [Errno 2] No such file or directory: '7119-220.jpg'

这看起来很奇怪,因为每次我运行代码时,它都会特别关注同一个文件。通过使用try和,除了这个FileNotFoundError,我没有得到任何输出。你知道吗

问题:我没有犯的错误是什么?你知道吗

import os
import matplotlib.pyplot as plt
import time
import numpy as np
from PIL import Image

imagesPath = 'Neural_Net-for-Concrete-Crack-Detection/Wall_crack_dataset/W/CW'

target_names = [item for item in os.listdir(imagesPath)
                if os.path.isdir(os.path.join(imagesPath, item))]
number_train_samples = sum([len(files) for _, _, files in os.walk(imagesPath)])  

image = np.zeros((256, 256), dtype=int)

total_number_samples = number_train_samples

print('Training a CNN Multi-Classifier Model ......')
print(' - # of trained samples: ', number_train_samples, 
       '\n - total # of samples: ', total_number_samples)

这件作品只计算图像文件的数量。你知道吗

from PIL import Image
import os
i=0
image = np.zeros((256, 256), dtype='uint8')

imagesPath = 'Neural_Net-for-Concrete-Crack-Detection/Wall_crack_dataset/W/CW'

for _, _, files in os.walk(imagesPath):
  for file in files:
    image = Image.open(file)

如果我在要打印的目录中指定一个特定的图像文件,则此代码工作得更好,但不是所有的。你知道吗


Tags: 文件pathin图像importnumberforos
1条回答
网友
1楼 · 发布于 2024-09-30 12:24:58

^{}产生一个3元组(dirpath, dirnames, filenames)。因此,您应该尝试打开os.path.join(dirpath, file),而不是file

from PIL import Image
import os
i=0
image = np.zeros((256, 256), dtype='uint8')

imagesPath = 'Neural_Net-for-Concrete-Crack-Detection/Wall_crack_dataset/W/CW'

for dirpath, _, files in os.walk(imagesPath):  # < 
  for file in files:
    image = Image.open(os.path.join(dirpath, file))  # < 

如果您需要一个dataset形状(n_samples, channels, height, width)PIL.Image,您可以这样做:

dataset_dir = "[DATASET_DIR]"
dataset = np.asarray([
    np.asarray(  # convert from PIL.Image to np.array
        Image.open(os.path.join(dirpath, img_fname))  # open image
    ).transpose((2,0,1))  # change from (H,W,C) to (C,H,W)
    for dirpath, _, fnames in os.walk(dataset_dir)  # scan the `dataset_dir`
    for img_fname in fnames  # for each file in `dataset_dir`
])

请注意,它要求所有图像具有相同的shape。你知道吗

相关问题 更多 >

    热门问题