(五)图像直方图绘制

图像直方图绘制

一、定义

图像直方图: 统计图像中每级像素出现的个数,以像素级为坐标,该像素级的像素个数值所画出的直方图

图像直方图由于其计算代价较小,且具有图像平移、旋转、缩放不变性等众多优点,广泛地应用于图像处理的各个领域,特别是灰度图像的阈值分割、基于颜色的图像检索以及图像分类。

python实现

import cv2
import matplotlib.pyplot as plt

def histogram(img_gray):
    '''
    求灰度图像的直方图
    :param img_gray: 灰度图像
    :return:
    '''
    histogram = [0 for x in range(256)]
    h,w = img_gray.shape
    for i in range(h):
        for j in range(w):
            histogram[img_gray[i][j]] = histogram[img_gray[i][j]]+1
    return histogram
def RGB_histogram(img):
    '''
    求彩色图像的直方图
    :param img: BGR图像或者RGB图像
    :return:
    '''
    Bhistogram = histogram(img[:,:,0])
    Ghistogram = histogram(img[:,:,1])
    Rhistogram = histogram(img[:,:,2])
    return Bhistogram,Ghistogram,Rhistogram

###读取灰度图并显示
img = cv2.imread('image0.JPG',1)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
plt.subplot(221)
plt.imshow(img_gray,cmap = "gray")

### 计算灰度直方图并显示
plt.subplot(222)
histogram_x = [x for x in range(256)]
Gray_histogram = histogram(img_gray)
plt.bar(histogram_x,Gray_histogram,width=1)

# 计算彩色直方图并显示
BGRhistogram = RGB_histogram(img)
plt.subplot(223)
plt.bar(histogram_x,BGRhistogram[0],color="blue",width=1)
plt.bar(histogram_x,BGRhistogram[1],color="green",width=1)
plt.bar(histogram_x,BGRhistogram[2],color="red",width=1)
# 使用直方图函数画直方图
plt.subplot(224)
img = img_gray.reshape(-1)  #将图像展开成一个一维的numpy数组
plt.hist(img, 256,width=2)  #将数据分为256组
plt.show()

1,size_16,color_FFFFFF,t_70)

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值