局部直方图均衡

时间:2013-11-20 02:10:40

标签: python image numpy filter histogram

我试图在python中使用一些图像分析(我必须使用python)。我需要进行全局和局部直方图均衡化。全局版本运行良好,但使用7x7足迹的本地版本会产生非常差的结果。

这是全球版本:

   import matplotlib.pyplot as plt
   import matplotlib.image as mpimg
   from scipy  import ndimage,misc
   import scipy.io as io
   from scipy.misc import toimage
   import numpy as n
   import pylab as py
   from numpy import *

   mat = io.loadmat('image.mat')
   image=mat['imageD']

   def histeq(im,nbr_bins=256):
     #get image histogram
     imhist,bins = histogram(im.flatten(),nbr_bins,normed=True)
     cdf = imhist.cumsum() #cumulative distribution function
     cdf = 0.6 * cdf / cdf[-1] #normalize
     #use linear interpolation of cdf to find new pixel values
     im2 = interp(im.flatten(),bins[:-1],cdf)
     #returns image and cumulative histogram used to map
     return im2.reshape(im.shape), cdf

   im=image
   im2,cdf = histeq(im)

要做本地版本,我试图使用像这样的通用过滤器(使用与之前加载的相同的图像):

   def func(x):
     cdf=[]
     xhist,bins=histogram(x,256,normed=True)
     cdf = xhist.cumsum() 
     cdf = 0.6 * cdf / cdf[-1] 
     im_out = interp(x,bins[:-1],cdf)
     midval=interp(x[24],bins[:-1],cdf)
     return midval

 print im.shape
 im3=ndimage.filters.generic_filter(im, func,size=im.shape,footprint=n.ones((7,7)))

有没有人对第二个版本无效的原因提出任何建议/想法?我真的被卡住了,任何评论都会非常感激!提前谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用scikit-image库执行全局和局部直方图均衡。从链接中骄傲地窃取,下面是片段。均衡是使用磁盘形状的内核(或覆盖区)完成的,但您可以通过设置kernel = np.ones((N,M))将其更改为正方形。

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

from skimage import data
from skimage.util import img_as_ubyte
from skimage import exposure
import skimage.morphology as morp
from skimage.filters import rank

# Original image
img = img_as_ubyte(data.moon())

# Global equalize
img_global = exposure.equalize_hist(img)

# Local Equalization, disk shape kernel
# Better contrast with disk kernel but could be different
kernel = morp.disk(30)
img_local = rank.equalize(img, selem=kernel)

fig, (ax_img, ax_global, ax_local) = plt.subplots(1, 3)

ax_img.imshow(img, cmap=plt.cm.gray)
ax_img.set_title('Low contrast image')
ax_img.set_axis_off()

ax_global.imshow(img_global, cmap=plt.cm.gray)
ax_global.set_title('Global equalization')
ax_global.set_axis_off()

ax_local.imshow(img_local, cmap=plt.cm.gray)
ax_local.set_title('Local equalization')
ax_local.set_axis_off()

plt.show()

Results of equalization