我想获得与minst.pkl.gz文件相同的结果 例如n,32,32,3n,1

问题描述

我尝试在mnist.pkl.gz文件之类的图像数据中运行cnn。 我将图片大小调整为32x32,并使其成为pkl文件

调整大小代码

img_size = (32,32)
def resize_img(img_path):
img_lists = os.listdir(img_path)
img_lists = natsort.natsorted(img_lists)
for img_name in img_lists:
    print(f'{img_path}{img_name}')
    image = Image.open(f'{img_path}{img_name}')
    image = image.resize(img_size)
    image.save(f'{img_path}{img_name}')
resize_img('train/')

腌制代码(来源:https://github.com/tikroute/mnist.pkl.gz-dataset-creator

print("Gonna process:\n\t %s"%glob_files)
dataset = []
for file_count,file_name in enumerate( sorted(glob(glob_files),key=len) ):
    #image = Image.open(file_name)
    img = Image.open(file_name) #.convert('LA') #tograyscale
    pixels = [f[0] for f in list(img.getdata())]
    dataset.append(pixels)
    if file_count % 1000 == 0:
        print("\t %s files processed"%file_count)
# outfile = glob_files+"out"
# np.save(outfile,dataset)
if len(loc_train_labels) > 0:
    df = pd.read_csv(loc_train_labels,names = ["class"])
    return np.array(dataset),np.array(df["class"])
else:
    return np.array(dataset)

我加载了pkl文件并检查了train_set的形状。 结果是:train_images-(2758,1024) train_labels-(2758,)

然后我执行了以下代码

train_images = train_images.reshape(train_images.shape[0],32,3)

但是发生了错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)<ipython-input-8-a380a618ad52> in <module>
----> 1 train_images = train_images.reshape(train_images.shape[0],3)
      2 valid_images = valid_images.reshape(valid_images.shape[0],3)
      3 test_images = test_images.reshape(test_images.shape[0],3)
      4 
      5 train_images = train_images.astype('float32')

  ValueError: cannot reshape array of size 2824192 into shape (2758,3)

我想获得诸如train_images-(2758,3)标签-(2758,1)之类的结果。

有没有办法得到这个结果?

解决方法

您使用的数据集没有3个RGB通道。但这是只有1个通道的灰度数据。

如果您计算:

2758 * 32 * 32 = 2824192

因此,请尝试使用此方法。

train_images = train_images.reshape(train_images.shape[0],32,1)

如果数据集中的每个图像的形状均为32 * 32 * 3,则

只需将img_size = (32,32)更改为img_size = (32,3)