图像的读取方式

PIL

1
2
3
4
5
6
7
8
9
10
11
from PIL import Image
import numpy as np

img = Image.open("1.jpg")
img.load()

array = np.asarrary(img)

img.show() # view the picture

img.save("./new_img.jpg")

PIL.Image包有很多其他的功能,比如:

1
2
# 从array生成图片convert it to a Pillow image
Image.fromarray(data,'RGB') # 如果mode='L',那么只有一个通道

cv2

1
2
3
4
5
6
import cv2

img = cv2.imread("./1.jpg") # 返回的img的channel顺序是BGR

grey_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转化为灰度图的模式
rgb_img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) # 转化为RGB的模式

cv2一个有用的method是resize

1
img = cv2.resize(raw_img,(width,height))

tensorflow

1
2
3
4
5
6
7
8
9
import tensorflow as tf

img = tf.keras.preprocessing.image.load_img("./i.jpg",target_size=(32,32,3)) # Loads an image into PIL format
img = tf.keras.preprocessing.image.img_to_array(img)

# 从array转化成PIL image 实例
img = tf.keras.preprocessing.image.array_to_img(array) # array是3D numpy array

tf.keras.utils.save_img(path,array)