pillow
from PIL import Image
import numpy as np
img = np.array(Image.open("1.png"))
print(img.shape, img.dtype)
#(689, 1461, 3) uint8
b = [255, 255, 255] - img
im = Image.fromarray(b.astype('uint8'))
im.save("test.png")
from PIL import Image
import numpy as np
img = np.array(Image.open("1.png").convert("L")) #变为灰度
print(img.shape, img.dtype)
#(689, 1461, 3) uint8
b = [255] - img
im = Image.fromarray(b.astype('uint8'))
im.save("test.png")
Matplotlib
- Matplotlib.pyplot相当于Matplotlib库的一个快捷方式
import matplotlib.pyplot as plt
plt.plot([1, 3, 4, 5 ,7], [1, 2, 3, 4, 5 ])
plt.ylabel("grade")
plt.axis([-1,10 ,0, 6]) #设置坐标系的范围
plt.savefig("test.png", dpi = 600)
plt.show()
中文显示
import matplotlib.pyplot as plt
plt.subplot(3, 2, 4)
plt.ylabel("纵轴", fontproperties = "SimHei")
plt.show()
文本显示
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(0.0 , 5.0, 0.02)
plt.plot(a, np.cos(2*np.pi*a), "r--")
plt.xlabel("横轴:时间t", fontproperties = "SimHei")
plt.ylabel("纵轴:振幅", fontproperties = "SimHei")
plt.title(r"正弦波实例 $y=cos(2\pi x)$", fontproperties = "SimHei", fontsize = 25)
plt.text(2, 1, r'$\mu=100$',fontsize = 15)
plt.axis([0,5, -2,2])
plt.grid(True)
plt.annotate(r'$\mu=100$', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(
facecolor = "black", shrink = 0.1, width = 2))
plt.show()
子区域划分
import matplotlib.pyplot as plt
plt.subplot2grid((3,3), (0,0), colspan=3)
plt.subplot2grid((3,3), (1,0), colspan=2)
plt.subplot2grid((3,3), (2,0), colspan=1)
plt.subplot2grid((3,3), (2,1), colspan=1)
plt.subplot2grid((3,3), (1,2), rowspan=2)
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f1RNJ047-1681137708690)(14.png)]
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax1 = plt.subplot(gs[2,0])
ax1 = plt.subplot(gs[2,1])
ax1 = plt.subplot(gs[1:,2])
plt.show()
图像绘制例子
饼图
import matplotlib.pyplot as plt
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode= explode, labels = labels,
autopct= '%1.1f%%', shadow=True, startangle=90)
plt.axis(True)
plt.show()
直方图
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
a = np.random.normal(1, 1, size=100)
print(a)
plt.hist(a, 20,) #第二个参数是bin的个数
plt.title("histgram")
plt.show()
散点图
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(111)
ax.plot(10*np.random.randn(100), 10*np.random.randn(100), '*')
ax.set_title("scatter")
plt.show()
Pandas
- 基于numpy扩展的数据处理库
import pandas as pd
a = pd.Series([9, 8, 7, 6], index=['a', 'b', 'c', 'd'])
print(a)
'''
a 9
b 8
c 7
d 6
dtype: int64
'''