欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

opencv 求图像灰度直方图以及直方图均衡化

程序员文章站 2022-04-02 11:24:20
import cv2import numpy as npimport matplotlib.pyplot as plt##彩色图像转为灰度图像def RGB2gray(img): img1=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) return img1##计算图像的灰度直方图def gethistgram(img): hist=np.zeros(256) rows=img.shape[0] cols=img.shape[1...

opencv 求图像灰度直方图以及直方图均衡化

图像的灰度直方图表示的是0-255之间图像每个灰度级在图像中的像素个数,因此灰度直方图横坐标表示的是0-255个灰度级别,纵坐标表示每个灰度级别的个数,因此求图像灰度直方图的代码可以表示为:

#hist表示255干个灰度级 hist=np.zeros(256) #rows,cols表示图像长宽用于求图像像素点 rows=img.shape[0] cols=img.shape[1] for i in range(rows): for j in range(cols): tmp=img[i][j]#tmp为图像中像素点对应的灰度值 hist[tmp]=hist[tmp]+1#在hist对应灰度值的位置加1 

对图像进行灰度直方图均衡化用于提高图像的对比度,-可以将每个灰度级的个数除以图像的整个像素数,得到每个灰度级在图像中的占比情况,对其进行累加,便可将整个灰度级平均分布到整个图像中,再乘以灰度级255得到均衡后的灰度直方图:
opencv 求图像灰度直方图以及直方图均衡化
其代码表述为:

rows=img.shape[0] cols=img.shape[1] trans=hist/(rows*cols)*255 for i in range(1,len(trans)): trans[i]=trans[i-1]+trans[i] 
import cv2 import numpy as np import matplotlib.pyplot as plt ##彩色图像转为灰度图像 def RGB2gray(img): img1=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) return img1 ##计算图像的灰度直方图 def gethistgram(img): hist=np.zeros(256) rows=img.shape[0] cols=img.shape[1] for i in range(rows): for j in range(cols): tmp=img[i][j] hist[tmp]=hist[tmp]+1 return hist ##直方图均衡化 def Equalhistgram(img,hist): rows=img.shape[0] cols=img.shape[1] trans=hist/(rows*cols)*255 for i in range(1,len(trans)): trans[i]=trans[i-1]+trans[i] return trans
        
img=cv2.imread('C:\\Users\\matebook13\\Pictures\\hist.png') gray_img=RGB2gray(img) gray_h=gray_img.copy() img_hist=gethistgram(gray_img) equal_hist=Equalhistgram(gray_img,img_hist) ##将图片灰度直方图均匀化 rows=gray_img.shape[0] cols=gray_img.shape[1] for i in range(rows): for j in range(cols): gray_h[i][j]=int(equal_hist[gray_h[i][j]]) cv2.imwrite('transform_img.jpg',cv2.hconcat([gray_img,gray_h])) plt.figure(figsize=(11,11)) plt.imshow(cv2.hconcat([gray_img,gray_h]),cmap='gray') plt.show() 

opencv 求图像灰度直方图以及直方图均衡化opencv 求图像灰度直方图以及直方图均衡化从图中可以看出经过直方图均衡化后的图片的对比度更加清晰。

本文地址:https://blog.csdn.net/weixin_42046696/article/details/108249402