#读取和显示文件
from matplotlib import image as mpimg
from matplotlib import pyport as plt
import numpy as np
%matplotlib inline
img1=mpimg.imread('cat.jpg')#照片的名称 (吧照片放在软件下载的同目录)
plt.imghow(img1)#显示照片
type(img1)#看是什么数据类型的照片
#img1.shape#照片的长宽高
#另一种导入图像的方法
import cv2
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline#inline方式显示
img2=cv2.imread('cat.jpg')
plt.imshow(img2)
type(img2)#查看变量类型
#此时图像的色彩是黑白灰的,因为CV2加载图像保存为BGR,而不是RGB的格式,可以用以下方法变换
img2=cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)
#转换颜色空间的函数,转换为之后就是彩色的了
plt.imshow(img2)
#另一个常用的图像处理库,PIL
from PIL import Image
import matplotlib.pyplot as plt
%matplotlib inline# 用inline方式显示
img3=Image.open('cat.jpg')
plt.imshow(img3)
type(img3)#得到的数据类型是JepgImage
#可以转换为numpy.array
import numpy as np
img3=np.array(img3)
#缩放图像
from PIL import Image
import matplotlib.pyplot as plt
%matplotlib inline# 用inline方式显示
orig_img=Image.fromarray(img3)
#从array类型开始读
o_h,o_w=orig_img.size
print('Original size',o_h,'x',o_w)
#目标图像
target_size=(200,200)
new_img=orig_img.resize(target_size)
n_h,n_w=new_img.size
print('new size:',n_h,'x',n_w)
fig=plt.figure(figsize=(12,12))
a=fig.add_subplot(2,1,1)#缩放之前
imgplot=plt.imshow(orig_img)
a.set_title('Before')
a=fig.add_subplot(2,1,2)
imgplot=plt.imshow(new_img)
a.set_title('After')
plt.show()
#图像缩放造成了图像形变,我们可以按照原比例缩放长宽高
from PIL import Image,ImageOps
orig_img=Image.open('cat.jpg')
o_h,o_w=orig_img.size
print('Original size',o_h,'x',o_w)
#按比例缩放
target_size=(200,200)
scaled_img=orig_img.copy()#拷贝原图,不影响原图
scaled_img.thumbnail(target_size,Image.ANTIALIAS)
n_h,n_w=scaled_img.size
print('new size:',n_h,'x',n_w)
#加一个白色的背景,便于观看,三个参数全是255
new_img=Image.new("RGB",(o_h,o_w),(255,255,255))
new_img.paste(scaled_img,(int((target_size[0]-scaled_img.size[0])/2),int((target_size[1]-scaled_img.sized[1])/2)))
n_h,n_w=new_img.size
print('new size:',n_h,'x',n_w)
#显示三图
a=fig.add_subplot(3,1,1)#缩放之前
imgplot=plt.imshow(orig_img)
a.set_title('origial')
a=fig.add_subplot(3,1,2)
imgplot=plt.imshow(scaled_img)
a.set_title('Scaled')
plt.show()
a=fig.add_subplot(3,1,3)
imgplot=plt.imshow(new_img)
a.set_title('REsized')
plt.show()