代码之家  ›  专栏  ›  技术社区  ›  Fat Cat

直方图均衡化Python(无Numpy和无打印)

  •  1
  • Fat Cat  · 技术社区  · 8 年前

    我正在尝试编写一个代码,用于增加灰度图像的对比度,使其更清晰。我似乎无法使用此代码。我试图获得像素中每个值的分布频率(不使用除cv2之外的任何模块),并获得累积分布频率,这样我就可以使用下面的等式更改值。知道我的代码出了什么问题吗?

    import cv2
    img=cv2.imread(raw_input())
    shape=img.shape
    row=shape[0]
    col=shape[1]
    
    def df(img): #to make a histogram (count distribution frequency)
        values=[]
        occurances=[]
        for i in range (len(img)):
            for j in img[i]:
                values.append(j)
                if j in values:
                    count +=3
                    occurances.append(count)
        return occurances
    
    def cdf (img): #cumulative distribution frequency
        values2=[]
        for i in values:
            j=0
            i=i+j
            j+1
            values2.append(i)
        return values2
    
    def h(img): #equation for the new value of each pixel
        h=((cdf(img)-1)/((row*col)-1))*255
        return h
    
    newimage=cv2.imwrite('a.png')
    

    这是我试图做的一个例子。 enter image description here

    提前谢谢你。

    2 回复  |  直到 8 年前
        1
  •  1
  •   R. S. Nikhil Krishna    8 年前

    这是一个经过一些修改的解决方案。它给出以下输出

    原件: original

    均衡: histequalized

    主要修改:

    1. 这个 df() cdf() 功能变得简单。执行时一定要打印他们的输出,以检查它是否与您期望的结果相匹配
    2. 这个 equalize_image() 函数通过从正常像素范围(即 range(0,256) )累积分布函数

    代码如下:

    import cv2
    img = cv2.imread(raw_input('Please enter the name of your image:'),0) #The ',0' makes it read the image as a grayscale image
    row, col = img.shape[:2]
    
    
    def df(img):  # to make a histogram (count distribution frequency)
        values = [0]*256
        for i in range(img.shape[0]):
            for j in range(img.shape[1]):
                values[img[i,j]]+=1
        return values
    
    
    def cdf(hist):  # cumulative distribution frequency
        cdf = [0] * len(hist)   #len(hist) is 256
        cdf[0] = hist[0]
        for i in range(1, len(hist)):
            cdf[i]= cdf[i-1]+hist[i]
        # Now we normalize the histogram
        cdf = [ele*255/cdf[-1] for ele in cdf]      # What your function h was doing before
        return cdf
    
    def equalize_image(image):
        my_cdf = cdf(df(img))
        # use linear interpolation of cdf to find new pixel values. Scipy alternative exists
        import numpy as np
        image_equalized = np.interp(image, range(0,256), my_cdf)
        return image_equalized
    
    eq = equalize_image(img)
    cv2.imwrite('equalized.png', eq)
    
        2
  •  1
  •   peterh Eli    8 年前

    如果您不知道,opencv提供了一个用于直方图均衡的内置函数,有文档记录 here .

    关于您的代码:

    分布频率(或直方图)计算不正确,因为您只计算图像中确实出现的颜色的频率。您应该计算所有颜色值的外观,即使它们没有出现。 此外,每次你的颜色再次出现时,你都会将该颜色的一个新元素添加到列表中,这没有多大意义。我不太确定+=3从哪里来。

    我会这样做:

    def df(img): #to make a histogram (count distribution frequency)
        values = [0] * 256
        for i in range(len(img)):
            for j in img[i]:
               values[j] += 1