使用python和opencv进行直方图均衡而不使用内置函数 [英] histogram equalization using python and opencv without using inbuilt functions

查看:65
本文介绍了使用python和opencv进行直方图均衡而不使用内置函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用过公式:((L-1)/MN) ni在哪里L是灰度总数,M N是图像大小,ni是累积频率

I have used formula: ((L-1)/MN)ni where L is total no of graylevels,MN is size of image, ni is cumulative frequency

但是我总是得到全黑的图像.我也尝试过使用其他图像.

But I am getting full black image always.I have tried with other images as well.

import numpy as np
import cv2

path="C:/Users/Arun Nambiar/Downloads/fingerprint256by256 (1).pgm"
img=cv2.imread(path,0)

#To display image before equalization
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


a=np.zeros((256,),dtype=np.float16)
b=np.zeros((256,),dtype=np.float16)
height,width=img.shape

#finding histogram
for i in range(width):
    for j in range(height):
    g=img[j,i]
    a[g]=a[g]+1
print(a)        


#performing histogram equalization

tmp=255/(height*width)

a[0]=tmp*a[0]
b[0]=round(a[0])

for g in range(1,width):
   a[g]=(a[g]*tmp)+(a[g-1]*tmp)
   b[g]=round(a[g])



print(b)


b=b.astype(np.uint8)
print(b)
for i in range(width):
    for j in range(height):
        g=img[j,i]
        img[j,i]=b[g]

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我正在附加图像这是我使用过的图像

推荐答案

均衡步骤的实现有些不正确.概率分布函数(PDF)的计算应取决于容器的数量,而不应取决于图像的宽度(尽管在这种情况下它们是相等的).请参阅下面的代码,其中包含纠正的均衡步骤实现.

The equalization step has been implemented somewhat incorrectly. The calculation of probability distribution function (PDF) should be up to the number of bins and not the image width (Although they are equal in this specific case). Please see the following code with the corrected implementation of equalization step.

import numpy as np
import cv2

path = "fingerprint256by256.pgm"
img = cv2.imread(path,0)

#To display image before equalization
cv2.imshow('image',img)
cv2.waitKey(0)


a = np.zeros((256,),dtype=np.float16)
b = np.zeros((256,),dtype=np.float16)

height,width=img.shape

#finding histogram
for i in range(width):
    for j in range(height):
        g = img[j,i]
        a[g] = a[g]+1

print(a)   


#performing histogram equalization
tmp = 1.0/(height*width)
b = np.zeros((256,),dtype=np.float16)

for i in range(256):
    for j in range(i+1):
        b[i] += a[j] * tmp;
    b[i] = round(b[i] * 255);

# b now contains the equalized histogram
b=b.astype(np.uint8)

print(b)

#Re-map values from equalized histogram into the image
for i in range(width):
    for j in range(height):
        g = img[j,i]
        img[j,i]= b[g]

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

在Ubuntu 14.04上使用Python 3.4和OpenCV 3.4进行了测试和验证.

Tested and verified on Ubuntu 14.04 with Python 3.4 and OpenCV 3.4.

这篇关于使用python和opencv进行直方图均衡而不使用内置函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆