统计一张图像的彩色直方图以及灰度直方图

本文详细介绍如何使用Python和OpenCV库绘制三通道彩色图像及灰度图像的直方图,包括代码实现与示例结果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)统计一张三通道图像的彩色直方图:
原图如下:
在这里插入图片描述

import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
def draw_colors_hist(source_path):
    '''
    draw the color histogram of one three channels picture
    '''
    source_image=cv2.imread(source_path)


    colors=['blue','green','red']
    for i in range(3):
        hist_total,hist_edges=np.histogram(source_image[:,:,i].ravel(),bins=256,range=(0,256))
        plt.plot(0.5*(hist_edges[:-1]+hist_edges[1:]),hist_total,label=colors[i],color=colors[i])
    plt.show()
    draw_colors_hist('0.jpg')#注意图片的命名,若含有中文字符,会无法读取到图像。

结果如下:
在这里插入图片描述
(2)统计一张图片的灰度直方图。

def draw_gray_hist(source_path):
   
    #draw the grey histogram of one three channels picture
  
    source_image=cv2.imread(source_path)
    gray_img=cv2.cvtColor(source_image,cv2.COLOR_BGR2GRAY)
    hist_total,hist_edges=np.histogram(gray_img[:,:].ravel(),bins=256,range=(0,256))
    plt.plot(0.5*(hist_edges[1:]+hist_edges[:-1]),hist_total,label='grey',color='gray')
    plt.show()
draw_gray_hist('1.jpg')

仍采用本文开头所示的速腾2019款照片。
结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值