PIL.Image更改圖片尺寸 將矩陣轉換成圖

按照比例縮小圖片並生成新的圖片

import os
from PIL import Image
ext = ['jpg','jpeg','png']
files = os.listdir('.')
 
def process_image(filename, mwidth=200, mheight=400):
    image = Image.open(filename)
    w,h = image.size
    if w<=mwidth and h<=mheight:
        print(filename,'is OK.')
        return 
    if (1.0*w/mwidth) > (1.0*h/mheight):
        scale = 1.0*w/mwidth
        new_im = image.resize((int(w/scale), int(h/scale)), Image.ANTIALIAS)
 
    else:
        scale = 1.0*h/mheight
        new_im = image.resize((int(w/scale),int(h/scale)), Image.ANTIALIAS)     
    new_im.save('new-'+filename)
    new_im.close()
 
for file in files:
    if file.split('.')[-1] in ext:
        process_image(file)

 圖片轉換成矩陣,矩陣數據轉換成圖片

# coding=gbk
from PIL import Image
import numpy as np
# import scipy
import matplotlib.pyplot as plt

def ImageToMatrix(filename):
    # 讀取圖片
    im = Image.open(filename)
    # 顯示圖片
#     im.show()  
    width,height = im.size
    im = im.convert("L") 
    data = im.getdata()
    data = np.matrix(data,dtype=‘float‘)/255.0
    #new_data = np.reshape(data,(width,height))
    new_data = np.reshape(data,(height,width))
    return new_data
#     new_im = Image.fromarray(new_data)
#     # 顯示圖片
#     new_im.show()
def MatrixToImage(data):
    data = data*255
    new_im = Image.fromarray(data.astype(np.uint8))
    return new_im



filename = ‘lena.jpg‘
data = ImageToMatrix(filename)
print data 
new_im = MatrixToImage(data)
plt.imshow(data, cmap=plt.cm.gray, interpolation=‘nearest‘)
new_im.show()
new_im.save(‘lena_1.bmp‘)

上面要先對圖片去除顏色,就是變成黑白的,轉換成二維數據矩陣,不去顏色的還要保存顏色的,然後後面轉換就不行了,下面利用Image.fromarray(data) 新建圖片

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章