OpenCV学习(9)-灰度直方图

本文介绍了一种使用Python实现灰度图像直方图绘制的方法。通过读取灰度图像,计算每个灰度级别的像素数量,并利用Matplotlib库进行可视化展示。此外,还展示了如何使用hist函数绘制相同直方图的过程。
# -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np
import matplotlib.pyplot as plt

def calcGrayHist(img):
    h,w=img.shape
    grayHist=np.zeros(256,np.uint64)
    for i in range(w):
        for j in range(h):
            grayHist[img[j][i]]+=1
    return grayHist

if __name__=="__main__":
   if len(sys.argv)>1 :
      img = cv2.imread(sys.argv[1],0)
   else:
      print('None')
   cv2.imshow('img',img)
   grayHist=calcGrayHist(img)
   x_range=range(256)
   #画出灰度直方图
   plt.plot(x_range,grayHist,linewidth=2,color='black')
   #设置坐标轴范围
   y_maxValue=np.max(grayHist)
   plt.axis([0,255,0,y_maxValue])
   plt.xlabel('gray level')
   plt.ylabel('number of pixels')
   #显示灰度直方图
   plt.show()
   
   h,w=img.shape
   pixelSequence=img.reshape([h*w,])
   numbins=256 #共多少组条状体
   histogram,bins,patch=plt.hist(pixelSequence,numbins,facecolor='red',histtype='bar')
   plt.xlabel('gray level')
   plt.ylabel('number of pixels')
   y_maxValue=np.max(hi
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值