2.生成28*28灰度图
有了9类共54000张黑白图后,需要对它进行进一步的处理,那就是把它弄成28*28的黑像素图像。主要思路就是对每类图像的文件夹进行遍历,然后resize文章来源:https://www.toymoban.com/news/detail-798968.html
直接上代码:文章来源地址https://www.toymoban.com/news/detail-798968.html
import torchvision.transforms as transforms
from PIL import Image
num=6000
for i in range(num):
# 读取原始图像
# original_image = Image.open('./pre_data0/{}_0.jpg'.format(i+1))
# original_image = Image.open('./pre_data1/{}_1.jpg'.format(i+1))
# original_image = Image.open('./pre_data2/{}_2.jpg'.format(i+1))
# original_image = Image.open('./pre_data3/{}_3.jpg'.format(i+1))
# original_image = Image.open('./pre_data4/{}_4.jpg'.format(i+1))
# original_image = Image.open('./pre_data5/{}_5.jpg'.format(i+1))
# original_image = Image.open('./pre_data6/{}_6.jpg'.format(i+1))
# original_image = Image.open('./pre_data7/{}_7.jpg'.format(i+1))
original_image = Image.open('./pre_data8/{}_8.jpg'.format(i+1))
# 定义转换
transform = transforms.Compose([
transforms.Grayscale(num_output_channels=1),
transforms.Resize((28, 28)),
transforms.ToTensor()
])
# 应用转换
transformed_image = transform(original_image).squeeze(0) # squeeze(pre_data0)用于去掉批处理维度
# print(transformed_image)
for i1 in range(28):
for j in range(28):
if transformed_image[i1][j] < 0.1:
transformed_image[i1][j] = 0
else:
transformed_image[i1][j] = 1
# 将张量转换为图像
transformed_image_PIL = transforms.ToPILImage()(transformed_image)
# 保存图像
# transformed_image_PIL.save('./aft_train_data0/{}_0.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_train_data1/{}_1.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_train_data2/{}_2.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_train_data3/{}_3.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_train_data4/{}_4.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_train_data5/{}_5.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_train_data6/{}_6.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_train_data7/{}_7.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_train_data8/{}_8.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data0/{}_0.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data1/{}_1.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data2/{}_2.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data3/{}_3.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data4/{}_4.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data5/{}_5.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data6/{}_6.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data7/{}_7.jpg'.format(i+1))
# transformed_image_PIL.save('./aft_test_data8/{}_8.jpg'.format(i+1))
# transformed_image_PIL.save('./testdata_png/{}_8.png'.format(i + 1))
transformed_image_PIL.save('./traindata_png/{}_8.png'.format(i + 1))
到了这里,关于《如何制作类mnist的金融数据集》——2.生成28*28灰度图的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!