# -*- coding: utf-8 -*-
"""
@author: 陨星落云
csdn博客地址: https://blog.csdn.net/qq_28368377
"""
import numpy as np
import imageio 
import matplotlib.pylab as plt


def rgb2gray(img):
    
    # 灰度计算公式
    gray = 0.2126*img[:,:,0] + 0.7152*img[:,:,1] + 0.0722*img[:,:,2]
    
    return gray.astype(np.uint8)

def compute_histogram(img):
    # 计算直方图
    tab = np.zeros(256)
    for i in np.unique(img):
        # print(i)
        tab[i] = np.bincount(img.flatten())[i]
    return tab.astype(np.uint64).tolist()

def image_stretch(img):
    # 图像拉伸
    minimum = img.min()
    maximum = img.max()
    a = 255/(maximum-minimum)
    b = -255*minimum/(maximum-minimum)

    return (a*img+b).astype(np.uint8)


if __name__ == "__main__":
    

    img = imageio.imread('Unequalized.jpg')# rgb图像转灰度图像
    # print(compute_histogram(img))
    # print(img)
    # 显示图像
    plt.figure(figsize=(20,16))
    
    plt.subplot(221)
    plt.imshow(img,cmap='gray')
    plt.subplot(222)
    plt.imshow(image_stretch(img),cmap='gray')
    plt.subplot(223)
    # print(compute_histogram(img))
    plt.plot(compute_histogram(img))
    plt.subplot(224)
    # print(compute_histogram(image_stretch(img)))
    plt.plot(compute_histogram(image_stretch(img)))
    plt.show()

结果:
在这里插入图片描述

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐