读取
import matplotlib.pyplot as plt
- 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') # 图片的保存
- 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)
- 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')
- 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)函数