图像预处理
加载图像
from PIL import Image
import matplotlib.pyplot as plt
img1 = Image.open('C:/Users/31035/Desktop/resize1.png')
plt.imshow(img1)
img1.size
另寻为
img = Image.open("scr1.jpg")
img.save("src1.bmp")
img.save("src1.tiff")
print(img.mode)
print(img.format)
图片转换模式
img_gray = img.convert("L")
plt.figure(figsize=(5,5))
plt.imshow(img_gray )
plt.show()
展示RGB三个通道
img2 = Image.open("src1.tiff")
imgr,imgg,imgb = img2.split()
plt.subplot(221)
plt.imshow(imgr,cmap="gray")
plt.title("R")
plt.subplot(222)
plt.imshow(imgg,cmap="gray")
plt.title("G")
plt.subplot(223)
plt.imshow(imgb,cmap="gray")
plt.title("B")
imgrgb = Image.merge("RGB",[imgr,imgg,imgb])
plt.subplot(224)
plt.imshow(imgrgb)
plt.title("RGB")
plt.show()
图像变数组
import numpy as np
arr_img_gray = np.array(img_gray)
print(arr_img_gray.shape)
print(arr_img_gray)
黑白颠倒
arr_img_new = 255 - arr_img_gray
plt.subplot(121)
plt.imshow(arr_img_gray,cmap="gray")
plt.subplot(122)
plt.imshow(arr_img_new,cmap="gray")
plt.show()
其他操作
img_small = img.resize((64,34))
plt.imshow(img_small)
plt.show()
翻转图片
img_flr= img.transpose(Image.FLIP_LEFT_RIGHT)
img_tp = img.transpose(Image.TRANSPOSE)
plt.subplot(121)
plt.imshow(img_flr)
plt.subplot(122)
plt.imshow(img_tp)
plt.show()
裁剪图片
img_cut = img.crop((0,0,300,300))
plt.subplot(121)
plt.imshow(img)
plt.subplot(122)
plt.imshow(img_cut)
plt.show()
minist数据集
加载
mnist = tf.keras.datasets.mnist
(train_x, train_y), (test_x, test_y) = mnist.load_data(r"C:\Users\31035\.keras\datasets\mnist.npz")
print('training set:',len(train_x))
print('testing set:',len(test_x))
print(train_x.shape,train_x.dtype)
print(train_y.shape,train_y.dtype)
显示几张图
for i in range(4):
num = np.random.randint(1,60000)
plt.subplot(1,4,i+1)
plt.axis("off")
plt.imshow(train_x[num],cmap='gray')
plt.title(train_y[num])
plt.show()