opencv实现直方图均衡

学习产出:



import cv2
import numpy as np
import matplotlib.pyplot as plt

def origin_histogram(image_matrix): #形参是矩阵
    #创建一个字典类型的数据结构,用于记录原图各个灰度值的频数
    histogram = {
     }
    for i in range(image_matrix.shape[0]):
        for j in range(image_matrix.shape[1]):
            k = image_matrix[i][j]
            if k in histogram:
                histogram[k] += 1
            else:
                histogram[k] = 1


    #根据灰度值进行从低至高的排序
    sorted_list = sorted(histogram)
    sorted_histogram = {
     }
    for j in range(len(sorted_list)):
        sorted_histogram[sorted_list[j]] = histogram[sorted_list[j]]
    return sorted_histogram


def equalization_histogram(histogram,image):
    pr = {
     }#建立概率分布映射表
    for i in histogram.keys():
        pr[i] = histogram[i] / (image.shape[0] * image.shape[1])
    tmp = 0
    for m in pr.keys():
        tmp += pr[m]
        pr[m] =  max(histogram) * tmp
    new_img = np.zeros((image.shape[0],image.shape[1]),dtype = np.uint8 )
    for k in range(image.shape[0]):
        for l in range(image.shape[1]):
            new_img[k][l] = pr[img[k][l]]
    return new_img

def GrayHist(image):
    # 计算灰度直方图
    row,column = image.shape[0],image.shape[1]
    grayHist = np.zeros([256],np.uint64)
    for i in range(row):
        for j in range(column):
            grayHist[image[i][j]] += 1
    return grayHist


#读取原始图像
img = cv2.imread('cell.jpg',cv2.IMREAD_GRAYSCALE)

#计算原图灰度直方图
origin_histogram = origin_histogram(img)
# #直方图均衡化
# new_img = equalization_histogram(origin_histogram,img)
# origin_grayHist = GrayHist(img)
# equalized_grayHist = GrayHist(new_img)
#
# x = np.arange(256)
# # 绘制灰度直方图
# plt.rcParams['font.sans-serif'] = 'SimHei'
# p = plt.figure(figsize=(9,8),num='细胞图')
# ax1 = p.add_subplot(2,2,1)
# plt.bar(x,origin_grayHist)
# plt.title('初始直方图')
# plt.ylabel("像素个数")
#
# ax2 = p.add_subplot(2,2,2)
# plt.xticks(())
# plt.yticks(())
# plt.imshow(img,cmap = plt.cm.gray )
# plt.title('初始图')
#
# ax3 = p.add_subplot(2,2,3)
# plt.bar(x, equalized_grayHist,width=1.5)
# plt.title("均衡直方图")
# plt.ylabel("像素个数")
#
# ax4 = p.add_subplot(2,2,4)
# plt.xticks(())
# plt.yticks(())
# plt.imshow(new_img,cmap=plt.cm.gray )
# plt.title('均衡后')
# plt.savefig('细胞均衡图片.jpg')
# plt.show()

你可能感兴趣的:(笔记,opencv,计算机视觉,图像识别)