这里写目录标题
- 局部直方图处理
局部直方图处理
因为像素是由基于整个图像的灰度的变换函数修改的。这种全局性方法适合于整体增强,但当目的是增强图像中几个小区域的细节时,通常就会失败。这是因为在这些小区域中,像素的数量对计算全局变换的影响可以忽略。解决方法是设计基于像素邻域的灰度分布的变换函数。
# opencv实现的局部直方图处理
img_ori = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH03/Fig0326(a)(embedded_square_noisy_512).tif', 0)
img_transform, _= my_calhist(img_ori)
# img_transform = cv2.equalizeHist(img_ori)plt.figure(figsize=(15, 6))
plt.subplot(1, 3, 1), plt.imshow(img_ori, cmap='gray', vmin=0, vmax=255), plt.title('Original')
plt.subplot(1, 3, 2), plt.imshow(img_transform, cmap='gray', vmin=0, vmax=255), plt.title(f'Global Equalize Hist')clahe = cv2.createCLAHE(clipLimit=255, tileGridSize=(3, 3))
img_transform = clahe.apply(img_ori)plt.subplot(1, 3, 3), plt.imshow(img_transform, cmap='gray', vmin=0, vmax=255), plt.title(f'Local Equalize Hist')
plt.tight_layout()
plt.show()
def my_calhist_local(img):"""histogram equalizationparam: input img: uint8[0, 255] grayscale imagereturn uint8[0, 255] grayscale image after histogram equalization"""
# hist, bins = my_hist(img, bins=256, normalized=True) #局部直方图的时候这个比较慢,改为了下面的Numpy,效果快好多hist, bins = np.histogram(img, bins=256, range=[0, 256], density=True)#--------------------------------Numpy-------------------hist_cumsum = np.round(np.cumsum(hist) * 255).astype(int)img_dst = hist_cumsum[img]return img_dstdef local_calhist(img_ori, grid_size=(3, 3)):"""Local histogram equalizationparam: input img_ori: input uint8[0, 255] grayscale imageparam: input grid_size: grid size of the local hist, size need to be uneven number like 1, 3, 5return local histogram equalization of image uint8[0, 255]"""height, width = img_ori.shapeimg_dst = img_ori.copy()m = grid_size[0]n = grid_size[1]padding_h = int((m - 1) / 2)padding_w = int((n - 1) / 2)img_pad = np.pad(img_ori.copy(), (padding_h, padding_w), mode='constant', constant_values=0)for h in range(padding_h, height + padding_h):for w in range(padding_w, width + padding_w):temp = my_calhist_local(img_pad[h-padding_h:h+padding_h+1, w-padding_w:w+padding_w+1])img_dst[h:h+1, w:w+1] = temp[padding_h, padding_w]return img_dst
# Numpy实现的局部直方图处理,效果比opencv好
img_ori = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH03/Fig0326(a)(embedded_square_noisy_512).tif', 0)# global histogram equalization
img_global = my_calhist_local(img_ori)# local histogram equalization
img_local = local_calhist(img_ori, grid_size=(3, 3))plt.figure(figsize=(15, 6))
plt.subplot(1, 3, 1), plt.imshow(img_ori, cmap='gray', vmin=0, vmax=255), plt.title('Original')
plt.subplot(1, 3, 2), plt.imshow(img_global, cmap='gray', vmin=0, vmax=255), plt.title(f'Global Equalize Hist')
plt.subplot(1, 3, 3), plt.imshow(img_local, cmap='gray', vmin=0, vmax=255), plt.title(f'Local Equalize Hist')
plt.tight_layout()
plt.show()