模糊处理在边沿检测和去噪声方面有较为广泛的应用。OpenCV中提供了4种模糊算法,列举如下:
本文将分别采用这4种算法对同一幅图像进行处理,并以图像的形式展现这几种算法之间的差别。
代码如下
import numpy
import argparse
import cv2
image = cv2.imread('1.jpg')
cv2.imshow("Original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
#[x,y] is the kernel for bluring
#the large kernel becomes, the more blurred imag will appear
#hstack is able to stack multiple images together
#using simple mean to average
blurred = numpy.hstack([
cv2.blur(gray, (3,3)),
cv2.blur(gray, (5,5)),
cv2.blur(gray, (7,7))])
#display two images in a figure
cv2.imshow("Blurring by average", blurred)
cv2.imwrite("1_blur_by_average.jpg", blurred)
if(cv2.waitKey(0)==27):
cv2.destroyAllWindows()
代码如下
import numpy
import argparse
import cv2
image = cv2.imread('1.jpg')
cv2.imshow("Original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
#[x,y] is the kernel for bluring
#the large kernel becomes, the more blurred imag will appear
#hstack is able to stack multiple images together
#using weighted mean
#where neighborhood pixels that are closer to the central pixel contribute more "weight" to the average
blurred = numpy.hstack([
cv2.GaussianBlur(gray, (3,3), 0),
cv2.GaussianBlur(gray, (5,5), 0),
cv2.GaussianBlur(gray, (7,7), 0)])
#display two images in a figure
cv2.imshow("Blurring by Gaussian", blurred)
cv2.imwrite("1_blur_by_Gaussian.jpg", blurred)
if(cv2.waitKey(0)==27):
cv2.destroyAllWindows()
代码如下:
import numpy
import argparse
import cv2
image = cv2.imread('1.jpg')
cv2.imshow("Original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
#[x,y] is the kernel for bluring
#the large kernel becomes, the more blurred imag will appear
#hstack is able to stack multiple images together
#the central pixel is replaced with the median of the neighborhood
#it is the most effective when removing salt-and-pepper noise
blurred = numpy.hstack([
cv2.medianBlur(gray, 3),
cv2.medianBlur(gray, 5),
cv2.medianBlur(gray, 7)])
#display two images in a figure
cv2.imshow("Blurring by Median", blurred)
cv2.imwrite("1_blur_by_Median.jpg", blurred)
if(cv2.waitKey(0)==27):
cv2.destroyAllWindows()
代码如下:
import numpy
import argparse
import cv2
image = cv2.imread('1.jpg')
cv2.imshow("Original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
#[x,y] is the kernel for bluring
#the large kernel becomes, the more blurred imag will appear
#hstack is able to stack multiple images together
#in order to reduce noise while maintaining edges
blurred = numpy.hstack([
cv2.bilateralFilter(gray, 5,21,21),
cv2.bilateralFilter(gray, 7,31,31),
cv2.bilateralFilter(gray, 9,41,41)])
#display two images in a figure
cv2.imshow("Blurring by Bilateral", blurred)
cv2.imwrite("1_blur_by_Bilateral.jpg", blurred)
if(cv2.waitKey(0)==27):
cv2.destroyAllWindows()
以下是4种模糊算法处理同一张图片的结果。