本次實驗所用圖片:
軟件:pycharm
一、直方圖

import cv2 as cv from matplotlib import pyplot as plt import numpy as np path = '1.jpg' img = cv.imread(path, 0) plt.hist(img.ravel(), 256, [0, 256]) plt.show()
運行上面的代碼,可以得出圖片的直方圖:
二、高斯濾波

# coding=utf-8 import cv2 import numpy as np image = cv2.imread("1.jpg", 0) lut = np.zeros(256, dtype=image.dtype) # 創建空的查找表 hist, bins = np.histogram(image.flatten(), 256, [0, 256]) cdf = hist.cumsum() # 計算累積直方圖 cdf_m = np.ma.masked_equal(cdf, 0) # 除去直方圖中的0值 cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min()) # 等同於前面介紹的lut[i] = int(255.0 *p[i])公式 cdf = np.ma.filled(cdf_m, 0).astype('uint8') # 將掩模處理掉的元素補為0 # 計算 result2 = cdf[image] result = cv2.LUT(image, cdf) cv2.imshow("OpenCVLUT", result) cv2.imshow("NumPyLUT", result2) cv2.waitKey(0) cv2.destroyAllWindows()
上述代碼分別用3×3和5×5的濾波器對圖像進行濾波處理,通過比較中央像素與周圍像素亮度的差值,改變中央像素的值為周圍模糊半徑內(3×3或5×5)像素點的平均值,顯然,模糊半徑越大,圖像會變得更模糊。這樣處理后的圖片相比於原圖片會變得更模糊,即模糊處理。
效果圖如下:
3×3效果圖 5×5效果圖
仔細看可以看出5×5的效果較3×3的更模糊。
三、直方圖均衡化

# coding=utf-8 import cv2 import numpy as np image = cv2.imread("1.jpg", 0) lut = np.zeros(256, dtype=image.dtype) # 創建空的查找表 hist, bins = np.histogram(image.flatten(), 256, [0, 256]) cdf = hist.cumsum() # 計算累積直方圖 cdf_m = np.ma.masked_equal(cdf, 0) # 除去直方圖中的0值 cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min()) # 等同於前面介紹的lut[i] = int(255.0 *p[i])公式 cdf = np.ma.filled(cdf_m, 0).astype('uint8') # 將掩模處理掉的元素補為0 # 計算 result2 = cdf[image] result = cv2.LUT(image, cdf) cv2.imshow("OpenCVLUT", result) cv2.imshow("NumPyLUT", result2) cv2.waitKey(0) cv2.destroyAllWindows()
灰度化處理 直方圖均衡化處理后
可以看出,圖像經過直方圖均衡化,圖像增強。