文章目录
1、灰度直方图
本文使用的是pyplot中的hist方法绘制灰度图像的直方图,并将每个像素值的个数保存到Grayresult.txt文件下。
2、代码实现
2.1 plt.hist
plt.hist(GrayImage.ravel(),256,density=1)
plt.show()
2.1.1 参数介绍
image.ravel():将二维图像转化为一维数组
hitsize:图像灰度级
ranges:像素范围
density:默认为0,纵坐标为像素出现频数,为1时,纵坐标为像素出现频率
2.1.2 hist完整代码
def StaticGray(GrayImage):
#使用hist方法绘制灰度直方图
#density设置为1时,直方图纵坐标为频率
#默认情况下为densirty=0,纵坐标为频数
plt.hist(GrayImage.ravel(),256,density=1)
plt.show()
pixel = GrayImage.ravel()
data = np.zeros((256,1))
for i in range(0,len(pixel)):
data[pixel[i]]+=1
for i in range(0,256):
file = open("Grayresult.txt","a")
file.write(str(i)+": "+str(int(data[i][0]))+"\n")
return;
2.2 cv2.calcHist
#使用cv.calcHist([srcimage],[channels],[mask],[hitsize],[range])
hist = cv.calcHist([GrayImage],[0],None,[256],[0,255])
plt.plot(hist,'r')
plt.show()
2.2.1 参数介绍
srcimage:源图像
channels:通道数。[0],[1],[2],灰度图像只用填写[0]。
mask:如果是作用在整张图,直接是None。
hitsize: 直方图的灰度级数,例如[0,255]一共256级,故参数为256
range: 像素值范围,为[0,255]
返回值:hist为(256,1)规格的数组,第i行代表像素i的个数
2.2.2 calcHist完整代码
def StaticGray(GrayImage):
hist = cv.calcHist([GrayImage],[0],None,[256],[0,255])
plt.plot(hist,'r')
plt.show()
for i in range(0,256):
file = open("Grayresult.txt","a")
file.write(str(i) + ": " + str(int(hist[i])) + "\n")
return;
3、效果呈现
3.1 hist方法
3.2 calcHist方法
说明:二者结果相同,只是hist中让density参数为1,纵坐标显示的是频率。