图片数据集的读取和保存

读取

import matplotlib.pyplot as plt
  1. plt.imread(path)
    plt读取到的已经是numpy形式的数据。(image.len, image.width, channel)一个简单的demo:
test_list = os.listdir(path)
test_image = np.zeros((len(test_list), example.shape[0], example.shape[1]))
for image in range(len(test_list)):
    test_image[image] = plt.imread(test_path + "\\" + test_list[image])
test_image = np.reshape(test_image, (test_image.shape[0], test_image.shape[1], test_image.shape[2], 1))   

plt.savefig('new.jpg') # 图片的保存  
  1. cv2.imread()
    import cv2
    注意如果路径是中文的,那么返回可能是None,所以一般还是把文件夹命名为英文的,防止出现意外的bug。
import cv2
img = cv2.imread('fur.jpg')
h,w,c = img.shape
cv2.imshow('window_title', img)
cv2.waitKey(5000) #里面的参数表示延迟多少毫秒,默认为0.当参数小于等于0时,可以理解为延迟无穷大毫秒,就是暂停了。不使用该函数的话会发现图片一闪而过,观察不到。
cv2.imwrite('new2.jpg',img) #保存

3.PIL 的Image
注意读出来的不是numpy格式。

from PIL import Image
import numpy as np
img = np.array(Image.open(path))
print(img)
print(img.shape)
  1. ImageDataGenerator批量读取
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1 / 255)  # 归一化
test_datagen = ImageDataGenerator(rescale=1 / 255)

conv_initialize = "he_uniform"

train_generator = train_datagen.flow_from_directory(train_dir,
                                                    target_size=(256, 256),
                                                    batch_size=80,
                                                    class_mode='binary')

test_generator = train_datagen.flow_from_directory(test_dir,
                                                   target_size=(256, 256),
                                                   batch_size=80,
                                                   class_mode='binary')
  1. torch自带的ImageFolder批量读取,使用DataLoader进行数据导入。


dataset_train = datasets.ImageFolder(root + '/train',
transform)

dataset_test = datasets.ImageFolder(root + '/val', transform)

train_loader = torch.utils.data.DataLoader(dataset_train, batch_size=BATCH_SIZE,
shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset_test, batch_size=BATCH_SIZE,
shuffle=True)

保存

当对象是图片时,使用 object.save(path)函数
在PIL.Image.open之后进行保存

img = Image.fromarray(np.uint8(img))先把numpy转化格式再保存
img.save(path+图片名字.jpg/tif/...)

在plt之后进行保存

plt.savefig('new.jpg')

当对象时二维数组时,使用 misc.imsave(path,object)函数

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值