Fu Xianjun. All Rights Reserved.所有素材来自于小傅老师。
任务一:直方图绘制
使用plt.hist绘制直方图
cv2.calcHist绘制直方图
任务二:使用掩膜进行直方图绘制
任务四:直方图均衡化
理解直图均衡化并能够利用函数使用函数calcHist实现。
任务五:直方图比较
直方图比较
创建 RGB 三通道直方图(直方图矩阵)
创建一个(16*16*16,1)的初始矩阵,作为直方图矩阵
16*16*16的意思为三通道每通道有16个bins
人为构建直方图矩阵的索引,该索引是通过每一个像素点的三通道值进行构建
该处形成的矩阵即为直方图矩阵
创建第一幅图的rgb三通道直方图(直方图矩阵)
直方图比较函数
import cv2
import numpy as np
def create_rgb_hist(image):
h, w, c = image.shape
rgbhist = np.zeros([16 * 16 * 16, 1], np.float32)
bsize = 256 / 16
for row in range(h):
for col in range(w):
b = image[row, col, 0]
g = image[row, col, 1]
r = image[row, col, 2]
index = int(b / bsize) * 16 * 16 + int(g / bsize) * 16 + int(r / bsize)
rgbhist[int(index), 0] += 1
return rgbhistdef hist_compare(image1, image2):
hist1 = create_rgb_hist(image1)
hist2 = create_rgb_hist(image2)
match1 = cv2.compareHist(hist1, hist2, cv2.HISTCMP_BHATTACHARYYA)
match2 = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)
match3 = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CHISQR)
print("巴氏距离:%s, 相关性:%s, 卡方:%s" %(match1, match2, match3))
img1 = cv2.imread("dog1.jpg")
cv2.imshow("dog1", img1)
img2 = cv2.imread("dog3.jpg")
cv2.imshow("dog3", img2)
hist_compare(img1, img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
直方图阈值法
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()
#大于阈值的都设置为255
threshImage_out[threshImage_out > thresh] = 255
threshImage_out[threshImage_out <= thresh] = 0
return thresh, threshImage_outif __name__ == "__main__":
img = cv2.imread('dog2.png')
thresh,threshImage_out = threshTwoPeaks(img)
print(thresh)
cv2.imshow('threshImage_out',threshImage_out)
cv2.waitKey(0)
cv2.destroyAllWindows()
好了今天的学习就到这了吧
我们下期再见!