1 图片转灰度或者黑白
from PIL import Image
col = Image.open("cat-tied-icon.png")
gray = col.convert('L')
gray.save(‘result_grey.png’)
bw = gray.point(lambda x: 0 if x<128 else 255, '1')
bw.save("result_bw.png")
2 PIL读取图片,更改尺寸
from PIL import Image
test = Image.open('4.jpg')
gray_image = test.convert('L') # 'L'表示灰度图像,'1'表示二值图像,
new_image = test.resize((28,28))
resize
是PIL是自带的更改尺寸函数,但会造成图片的变形
def letterbox_image(image, size):
'''resize image with unchanged aspect ratio using padding'''
iw, ih = image.size
w, h = size
scale = min(w/iw, h/ih)
nw = int(iw*scale)
nh = int(ih*scale)
image = image.resize((nw,nh), Image.BICUBIC)
#Image.new生成新的图片,彩色图片mode='RGB',灰色图片mode='L'
new_image = Image.new('L', size, 128)
new_image.paste(image, ((w-nw)//2, (h-nh)//2))
return new_image
3 读取图片,变更shape,相互转换
from PIL import Image
import numpy as np
test = Image.open('test.jpg')
atrr = np.array(test)
#atrr = atrr/255 #归一化
#变更shape有多种方式,如下
atrr_3d = np.expand_dims(atrr, axis=0)
#atrr_