Opencv Python 简明教程

OpenCV Python - Image Filtering

图像基本上是像素矩阵,表示为 0 到 255 之间的二进制值,对应于灰度值。彩色图像将是一个三维矩阵,具有对应于 RGB 的多个通道。

An image is basically a matrix of pixels represented by binary values between 0 to 255 corresponding to gray values. A color image will be a three dimensional matrix with a number of channels corresponding to RGB.

图像滤波是对像素值进行平均的过程,目的是改变原始图像的色调、亮度、对比度等。

Image filtering is a process of averaging the pixel values so as to alter the shade, brightness, contrast etc. of the original image.

通过应用低通滤波器,我们可以去除图像中的任何噪声。高通滤波器有助于检测边缘。

By applying a low pass filter, we can remove any noise in the image. High pass filters help in detecting the edges.

OpenCV 库提供 cv2.filter2D() 函数。它通过一个大小为 3X3 或 5X5 等的正方形矩阵内核对原始图像进行卷积。

The OpenCV library provides cv2.filter2D() function. It performs convolution of the original image by a kernel of a square matrix of size 3X3 or 5X5 etc.

卷积将一个内核矩阵横向和纵向滑动跨越图像矩阵。对于每个位置,将内核下方的所有像素相加,取内核下方的像素的平均值,并将中心像素替换为平均值。

Convolution slides a kernel matrix across the image matrix horizontally and vertically. For each placement, add all pixels under the kernel, take the average of pixels under the kernel and replace the central pixel with the average value.

对所有像素执行此操作以获取输出图像像素矩阵。参考如下给出的图表 −

Perform this operation for all pixels to obtain the output image pixel matrix. Refer the diagram given below −

pixel matrix

cv2.filter2D() 函数需要输入数组、内核矩阵和输出数组参数。

The cv2.filter2D() function requires input array, kernel matrix and output array parameters.

Example

下图使用此函数获得二维卷积的平均图像结果。相关的程序如下 −

Following figure uses this function to obtain an averaged image as a result of 2D convolution. The program for the same is as follows −

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('opencv_logo_gs.png')
kernel = np.ones((3,3),np.float32)/9
dst = cv.filter2D(img,-1,kernel)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(dst),plt.title('Convolved')
plt.xticks([]), plt.yticks([])
plt.show()

Output

pixel matrixs

Types of Filtering Function

OpenCV 中的其他类型滤波功能包括 −

Other types of filtering function in OpenCV includes −

  1. BilateralFilter − Reduces unwanted noise keeping edges intact.

  2. BoxFilter − This is an average blurring operation.

  3. GaussianBlur − Eliminates high frequency content such as noise and edges.

  4. MedianBlur − Instead of average, it takes the median of all pixels under the kernel and replaces the central value.