本文通过python实现图像的加噪去噪: 具体代码如下(含详细注释):
import cv2 as cv
import skimage
import numpy as np
def boxBlur(img):
blur = cv.boxFilter(img, -1, (5, 5))
return blur
def gaussianBlur(img):
blur = cv.GaussianBlur(img, (5, 5), 1.5)
return blur
def main():
path = r"C:\Users\Administrator\Desktop\lds.jpg"
img = cv.imread(path)
start_t = cv.getTickCount()
gauss_noiseImg = skimage.util.random_noise(img, mode='gaussian')
gauss_noiseImg = gauss_noiseImg
salt_noiseImg = skimage.util.random_noise(img, mode='salt')
lb_gauss1 = cv.medianBlur(gauss_noiseImg.astype('float32'), 1)
lb_salt1 = cv.medianBlur(salt_noiseImg.astype('float32'), 1)
lb_gauss3 = cv.medianBlur(gauss_noiseImg.astype('float32'), 3)
lb_salt3 = cv.medianBlur(salt_noiseImg.astype('float32'), 3)
lb_gauss5 = cv.medianBlur(gauss_noiseImg.astype('float32'), 5)
lb_salt5 = cv.medianBlur(salt_noiseImg.astype('float32'), 5)
print(gauss_noiseImg.dtype, "gaussian noisy image dtype")
print(gauss_noiseImg.shape, "gaussian noisy image shape")
print(salt_noiseImg.dtype, "salt noisy image dtype")
print(salt_noiseImg.shape, "salt noisy image shape")
cv.namedWindow("Original Image", cv.WINDOW_NORMAL)
cv.imshow('Original Image', img)
cv.namedWindow("Added Gaussian Noise Image", cv.WINDOW_NORMAL)
cv.imshow('Added Gaussian Noise Image', gauss_noiseImg)
cv.namedWindow("Added Salt Noise Image", cv.WINDOW_NORMAL)
cv.imshow('Added Salt Noise Image', salt_noiseImg)
cv.namedWindow("lbguass Image1", cv.WINDOW_NORMAL)
cv.imshow('lbguass Image1', lb_gauss1)
cv.namedWindow("lbsalt Image1", cv.WINDOW_NORMAL)
cv.imshow('lbsalt Image1', lb_salt1)
cv.namedWindow("lbguass Image3", cv.WINDOW_NORMAL)
cv.imshow('lbguass Image3', lb_gauss3)
cv.namedWindow("lbsalt Image3", cv.WINDOW_NORMAL)
cv.imshow('lbsalt Image3', lb_salt3)
cv.namedWindow("lbguass Image5", cv.WINDOW_NORMAL)
cv.imshow('lbguass Image5', lb_gauss5)
cv.namedWindow("lbsalt Image5", cv.WINDOW_NORMAL)
cv.imshow('lbsalt Image5', lb_salt5)
stop_t = ((cv.getTickCount() - start_t) / cv.getTickFrequency()) * 1000
print(stop_t, "ms")
cv.waitKey(0)
cv.destroyAllWindows()
if __name__ == "__main__":
main()
输出结果: 对比得出:经过中值滤波5的滤波后噪声比中值滤波3滤波后的图像噪声更少,但是图像也更模糊一些。 问题:在进行中值滤波7去噪时代码出错, 即如果要进行medianBlur,ksize=3,5就没有问题,只要ksize >=7 就开始报错。 可能原因:输入1-,3-,4-通道的图像; 当ksize 是 3 或 5时,图像的深度应该时 CV_8U, CV_16U, or CV_32F, 如果孔径更大, 它只可能是CV_8U. 后面需要用到OPENCV图形转换,后续将继续学习实现…
|