一、Matplotlib 简介
Matplotlib 是一个绘图库,我们所看到的直方图、折线图、饼状图、箱线图等都可以用它来绘制,其提供的绘图功能十分的强大,通过各种参数的搭配使用,可以绘制出更加生动优美的图案。
二、部分函数功能及参数介绍
from matplotlib import pyplot as plt
1. plt.hist() —— 绘制直方图
(1)函数原型:
matplotlib.pyplot.hist( arr, bins=10, normed=0, facecolor=‘black’, edgecolor=‘black’,alpha=1,histtype=‘bar’ )
可以看到,大多数参数都有默认值,所以我们把焦点放在常用的几个参数上:
arr:需要计算直方图的一维数组,通常我们将图片转换为一维,例如img.flatten()
bins:直方图的柱数,默认值为10,但画图时通常设置其为256
facecolor:直方图颜色
示例代码:
import cv2
import matplotlib.pyplot as plt
import numpy as np
img=cv2.imread("island.png")
b,g,r=cv2.split(img)
img=cv2.merge([r,g,b])
#划分子图
img1=plt.subplot(1,2,1)
plt.title("Origin")
plt.imshow(img)
img2=plt.subplot(1,2,2)
plt.title("Histogram")
# 2-blue
ab=img[:,:,2].flatten()#注意,这里通道变化,因为前面将imread读取方式更改为plt方式
plt.hist(ab, bins=256, facecolor='b',edgecolor='b')
# 1-green
ag=img[:,:,1].flatten()
plt.hist(ag, bins=256, facecolor='g',edgecolor