histogram equalization using python and opencv without using inbuilt functions

寵の児 提交于 2021-01-28 08:28:17

问题


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()

I am attaching image this is image i have used


回答1:


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()

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



来源:https://stackoverflow.com/questions/50578876/histogram-equalization-using-python-and-opencv-without-using-inbuilt-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!