我正在尝试使用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)))

是否有人对第二个版本为什么不起作用有任何建议/想法?我真的很卡住,任何评论将不胜感激!提前致谢!

最佳答案

您可以使用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()

关于python - 局部直方图均衡,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20086032/

10-13 05:45