Python+OpenCV(七)——直方图及其应用
学习视频:python+opencv3.3视频教学 基础入门 其他学习记录: Python+OpenCV(一)——基础操作 Python+OpenCV(二)——Numpy模块 Python+OpenCV(三)——色彩空间 Python+OpenCV(四)——像素运算 Python+OpenCV(五)——ROI和泛洪填充 Python+OpenCV(六)——均值/中值/自定义/高斯模糊、高斯噪声处理、高斯双边滤波 源码如下:
# -*- coding = utf-8 -*-
# @Time : 2021/8/2 19:08
# @Author : 西兰花
# @File : OpenCV02.py
# @Software : PyCharm
import cv2 as cv # 引入OpenCV模块
import numpy as np
import matplotlib.pyplot as plt
def plot_dome(image):
plt.hist(image.ravel(), 256, [0, 256])
plt.show()
def image_hist(image):
color = ('blue', 'green', 'red')
for i, color in enumerate(color):
hist = cv.calcHist([image], [1], None, [256], [0, 256])
plt.plot(hist, color=color)
plt.xlim([0, 256])
plt.show()
def equalHist_demo(image): # 全局均衡化(灰度图像),增强对比度
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
dst = cv.equalizeHist(gray)
cv.imshow("equalHist_demo", dst)
def clahe_demo(image): # 局部均衡化(灰度图像),增强了对比度
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
clahe = cv.createCLAHE(clipLimit=0.5, tileGridSize=(8, 8))
dst = clahe.apply(gray)
cv.imshow("clahe_demo:", dst)
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 = np.int(b / bsize) * 16 * 16 + np.int(g / bsize) * 16 + np.int(r / bsize)
rgbHist[np.int(index), 0] = rgbHist[np.int(index), 0] + 1
return rgbHist
def hist_compare(image1, image2):
hist1 = create_rgb_hist(image1)
hist2 = create_rgb_hist(image2)
match1 = cv.compareHist(hist1, hist2, cv.HISTCMP_BHATTACHARYYA)
match2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL)
match3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR)
print("巴氏距离: %s, 相关性: %s, 卡方: %s " %(match1, match2, match3))
print("------ Hello OpenCV ------")
src1 = cv.imread("C:/Users/Administrator/Pictures/PS/4.jpg") # 读取图像
cv.imshow("input image_12.jpg", src1) # 显示图像
# plot_dome(src)
# image_hist(src)
# equalHist_demo(src)
# clahe_demo(src)
src2 = cv.imread("C:/Users/Administrator/Pictures/PS/3.jpg") # 读取图像
src3 = cv.imread("C:/Users/Administrator/Pictures/PS/image_3.jpg----after.jpg") # 读取图像
cv.imshow("input image_3.jpg", src2) # 显示图像
cv.imshow("input image_image_3.jpg----after.jpg", src3) # 显示图像
hist_compare(src2, src3)
cv.waitKey(0)
cv.destroyAllWindows() # 销毁/关闭所有窗口
输出结果:
1.直方图的使用
2.均衡化,增强对比度 全局均衡化、局部均衡化 3.巴氏距离、相关性、卡方
|