前言
直方图是图像处理过程中的一种非常重要的分析工具。直方图从图像内部灰度级的角度对图像进行表述,包含十分丰富而重要的信息。从直方图的角度对图像进行处理,可以达到增强图像显示效果的目的。
一、直方图是什么?
从统计的角度讲,直方图是图像内灰度值的统计特性与图像灰度值之间的函数,直方图统计图像内各个灰度级出现的次数。从直方图的图形上观察,横坐标是图像中各像素点的灰度级,纵坐标是具有灰度级(像素值)的像素个数。
二、使用步骤
1.引入库
代码如下:
import cv2
import numpy as np
2.读入数据
代码如下:
import cv2
import numpy as np
def calcGrayHist(grayimage):
rows,cols = grayimage.shape
print(grayimage.shape)
grayHist = np.zeros([256],np.uint64)
for r in range(rows):
for c in range(cols):
grayHist[grayimage[r][c]] += 1
return grayHist
def threshTwoPeaks(image):
if len(image.shape) == 2:
gray = image
else:
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
print(666666)
histogram = calcGrayHist(gray)
maxLoc = np.where(histogram==np.max(histogram))
firstPeak = maxLoc[0][0]
measureDists = np.zeros([256],np.float32)
for k in range(256):
measureDists[k] = pow(k-firstPeak,2)*histogram[k]
maxLoc2 = np.where(measureDists==np.max(measureDists))
secondPeak = maxLoc2[0][0]
thresh = 0
if firstPeak > secondPeak:
temp = histogram[int(secondPeak):int(firstPeak)]
minloc = np.where(temp == np.min(temp))
thresh = secondPeak + minloc[0][0] + 1
else:
temp = histogram[int(firstPeak):int(secondPeak)]
minloc = np.where(temp == np.min(temp))
thresh = firstPeak + minloc[0][0] + 1
threshImage_out = gray.copy()
threshImage_out[threshImage_out > thresh] = 255
threshImage_out[threshImage_out <= thresh] = 0
return thresh, threshImage_out
if __name__ == "__main__":
img = cv2.imread("mao.jpg")
thresh,threshImage_out = threshTwoPeaks(img)
print(thresh)
cv2.imshow("threshImage_out",threshImage_out)
cv2.waitKey(0)
cv2.destroyAllWindows()
3.代码解释分析
解释如下:
4.代码展示效果
效果图如下:
总结
以下是运用到的个别单词的意思解释:
bin箱子
img.ravel()将img这张三维图像摊平成一维数组
Histogram直方图
channels指通道编号
mask掩膜图像
ranges像素值范围
merge合并