#引入库
from matplotlib import image as mpimg#库一
from matplotlib import pyplot as plt
import numpy as np
#%matplotlib inline
import cv2#库二
from PIL import Image#库三
#读图片的几种方法,
"""方法1"""
img1 = mpimg.imread("car.jpg")
plt.imshow(img1)
plt.show() ###有这句话才可以在pycharm显示图片
print(type(img1))
#这个函数将这个张图片直接读为np.ndarray
#
print(img1.shape)
#查看形状
#(301, 500, 3)
"""方法2"""
img2 = cv2.imread("car.jpg")#读图RGB的顺序是BGR
plt.imshow(img2)
plt.show()
print(type(img2))
img2 = cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)#函数转换机制转换为常见的格式
plt.imshow(img2)
plt.show()
"""方法3"""
img3 = Image.open("car.jpg")
plt.imshow(img3)
plt.show()
print(type(img3))
#
#由于格式不同,需要转化为jpg
img3 = np.array(img3)
print(type(img3))
"""直接读为一个np.array图像"""
np.save("car.npy",img3)
img3 = np.load("car.npy")
plt.imshow(img3)
plt.show()
#缩放图片
from matplotlib import image as mpimg
from matplotlib import pyplot as plt
from PIL import Image,ImageOps
"""按200x200的比例缩放"""
img1 = mpimg.imread("car.jpg")
orig_img = Image.fromarray(img1)
o_h,o_w = orig_img.size
#np的用shape,PIL的用size
print("原图尺寸:",o_h,"x",o_w)
target_size = (200,200)
new_img = orig_img.resize(target_size)
n_h,n_w = new_img.size
print("新图尺寸:",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("now")
plt.show()
"""按照图片比例缩放"""
orig_img = Image.open("car.jpg")
o_h,o_w = orig_img.size
print("原图尺寸:",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("新图尺寸:",n_h,"x",n_w)
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.size[1])/2)))
#将生成的图放在这个白图上面,然后有具体的位置
n_h,n_h = new_img.size#该图片的尺寸,是属性,不是方法
fig = plt.figure(figsize=(12,12))
#要显示一组图,最外面的那个框
a = fig.add_subplot(3,1,1)
#显示第一个位置
imgplot = plt.imshow(orig_img)
a.set_title("original")
a = fig.add_subplot(3,1,2)
imgplot = plt.imshow(scaled_img)
a.set_title("scaled_img")
a = fig.add_subplot(3,1,3)
imgplot = plt.imshow(new_img)
a.set_title("new_img")
plt.show()