OpenCV Python 如何在图像上执行SQRBox滤波操作
我们可以使用 cv2.sqrBoxFilter() 函数在图像上执行SQRBox滤波操作。它计算与滤波器重叠的像素值的平方的归一化和。我们使用以下语法表示该方法:
cv2.sqrBoxFilter(img, ddepth, ksize, borderType)
其中, img 为输入图像, ddepth 为输出图像的深度, ksize 为卷积核大小, borderType 为用于外推图像外部像素的边界模式。
步骤
要执行SQRBox滤波操作,可以按照以下步骤进行:
- 导入所需的库。在以下所有示例中,所需的Python库是 OpenCV 。请确保您已经安装了它。
-
使用cv2.imread()方法读取输入图像。指定图像的完整路径和图像类型(即png或jpg)
-
对输入图像应用 cv2.sqrBoxFilter() 滤波器。我们向函数传递 ddepth,ksize,borderType 。我们可以调整 ksize 以获得更好的结果。
sqrbox = cv2.sqrBoxFilter(img, cv2.CV_32F, ksize=(1,1), borderType = cv2.BORDER_REPLICATE)
- 显示经过 sqrBoxFilter 过滤的图像。
我们将在接下来的示例中使用此图像作为输入文件。
示例
在这个Python程序中,我们对颜色输入图像应用1×1的SQRBox滤波器。
# import required libraries
import cv2
# Read the image.
img = cv2.imread('car.jpg')
# apply sqrBoxFilter on the input image
sqrbox = cv2.sqrBoxFilter(img, cv2.CV_32F, ksize=(1,1),
borderType = cv2.BORDER_REPLICATE)
print("We applied sqrBoxFilter with ksize=(1,1)")
# Save the output
cv2.imshow('sqrBoxFilter', sqrbox)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出
在执行时,它将产生以下输出 —
We applied sqrBoxFilter with ksize=(1,1)
我们得到下面的窗口显示输出 −
示例
在这个Python程序中,我们对一个5×5的核大小的二进制图像应用了SQRBox滤波器。
# import required libraries
import cv2
# Read the image
img = cv2.imread('car.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 150, 255,cv2.THRESH_BINARY)
# apply sqrBoxFilter on the input image
sqrbox = cv2.sqrBoxFilter(thresh, cv2.CV_32F, ksize=(5,5),
borderType = cv2.BORDER_REPLICATE)
print("We applied sqrBoxFilter with ksize=(5,5)")
# Display the outputs
cv2.imshow('Gray Image', gray)
cv2.waitKey(0)
cv2.imshow('Threshold', thresh)
cv2.waitKey(0)
cv2.imshow('sqrBoxFilter', sqrbox)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出
在执行时,它将产生以下 输出 −
We applied sqrBoxFilter with ksize=(5,5)
以下是显示输出的三个窗口: