PIL
PIL库支持图像存储、显示和处理,能够处理几乎所有格式的图片
Image读取图片为Image类型,可直接显示
from PIL import Image
img = Image.open('youyou.jpeg')#打开图片
img.show()#显示图片
img.save('youyou.jpg')#保存图片
图像转化为numpy类型后shape为[h,w,c],chanel顺序为[r,g,b]
import numpy as np
img = np.array(img)
print(img[:,:,0])#r通道
array([[231, 231, 231, ..., 238, 238, 237],
[231, 231, 231, ..., 238, 238, 237],
[231, 231, 231, ..., 238, 238, 237],
...,
[134, 134, 134, ..., 107, 108, 109],
[133, 133, 133, ..., 108, 109, 109],
[132, 132, 132, ..., 108, 109, 110]], dtype=uint8)
numpy类型保存前须转为Image类型
img = Image.fromarray(img)
img.show()#显示图片
img.save('youyou.jpg')#保存图片
cv2
cv2读取图片为numpy类型,shape为[h,w,c],chanel顺序为[b,g,r]
import cv2 as cv
img = cv.imread('youyou.jpeg')#打开图片
print(img[:,:,2])#r通道
array([[199, 199, 199, ..., 207, 207, 206], [199, 199, 199, ..., 207, 207, 206], [199, 199, 199, ..., 207, 207, 206], ..., [165, 165, 165, ..., 147, 148, 149], [164, 164, 164, ..., 148, 149, 149], [163, 163, 163, ..., 148, 149, 150]], dtype=uint8)
cv.imshow('youyou',img)#显示图片
cv.imwrite('youyou.png',img)#保存图片
matplotlib
matplotlib 是python最著名的2D绘图库,适合交互式制图
plt可显示Image类型图片
import matplotlib.pyplot as plt
img = Image.open('youyou.jpeg')#打开图片
plt.figure("youyou")
plt.imshow(img)
plt.show()
plt也可显示numpy类型图片
import matplotlib.pyplot as plt
img = cv.imread('youyou.jpeg')#打开图片
plt.figure("youyou")
plt.imshow(img)
plt.show()
注意cv2读取的图片通道为bgr,若用其他工具显示需要转换通道
import matplotlib.pyplot as plt
img = cv.imread('youyou.jpeg')#打开图片
img1 = img.copy() #改变img1的时候不改变img
img1[:,:,0] = img[:,:,2]
img1[:,:,1] = img[:,:,1]
img1[:,:,2] = img[:,:,0] #cv2读取的是bgr,转换成rgb就要做一下变通
img = img1
plt.figure("youyou")
plt.imshow(img)
plt.show()