按照比例缩小图片并生成新的图片
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) 新建图片