解读Opencv中Filter2D函数的补全方式
作者:sq_damowang 时间:2022-06-16 23:11:15
环境
OpenCV3.4.16(C++)
opencv-contrib-python 4.5.4.60(Python)
验证
Opencv函数filter2d(),一般用于图像卷积,其中关键参数,输入图像src,输出图像dst,卷积核kernel。
一般来说通过kernel进行卷积之后图像尺寸要比原图像尺寸小一点,为了保持图像大小不变,filter2d在进行运算前对src进行了补全操作。
通常补全操作有补零,图像边缘扩展等,但是这都不是filter2d()的补全方式,尝试了多次,发现,无论是C++还是python,这里的补全方式均为沿边缘镜像扩展。
C++举例
代码如下所示
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat src = (Mat_<uint8_t>(1, 8) << 2,4,6,8,10,12,14,16);
Mat kernel = (Mat_<float>(1, 2) << 1, 1);
Mat dst1;
filter2D(src, dst1, -1, kernel);
cout<<"dst1:"<<dst1<<endl;
return 0;
}
得到结果为:
对[[2, 4, 6, 8, 10, 12, 14, 16]]进行沿边缘镜像扩展(这里其实应该扩展到shape为(3,10),但是由于kernel的shape为(1,2),就只进行这个维度扩展了),得到
[[4,2,4,6,8,10,12,14,16,14]],然后kernel为[[1,1]],计算得到
[[4+2,2+4,4+6,6+8,8+10,10+12,12+14,14+16]];即为
[[6,6,10,14,18,22,26,30]]
至于为什么计算了4+2而没有计算16+14,那是因为filter2D的另一个参数anchor,此处默认值为(-1,-1),意为指向kernel的中心位置,因为此处kernel大小为(1,2),默认位置即为(0,1),若修改anchor参数为(0,0),那么kernel的锚点就在前面,这样就不会计算前面的4+2,而是计算尾部的16+14了,最后的输出也就变为[[6,10,14,18,22,26,30,30]]
Python举例
输入图像src,与卷积核kernel如下所示
输入src沿边缘镜像扩展后变为
最后进行卷积,得到最终结果
Python代码如下所示
import cv2
import numpy as np
src = np.array(([4,2,1],[2,1,3],[5,1,1]), dtype="float32")
kernel = np.array(([1,2,3],[4,5,6],[-1,-2,-1]), dtype="float32")
dst = cv2.filter2D(src, -1, kernel)
print(dst)
得到最终结果如下:
来源:https://blog.csdn.net/sq_damowang/article/details/123757974
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python源码学习之PyType_Type和PyBaseObject_Type详解
![](https://img.aspxhome.com/file/2023/3/61733_0s.png)
asp如何用SA-FileUp上传多个文件?
Python jieba库用法及实例解析
![](https://img.aspxhome.com/file/2023/8/97598_0s.png)
python文件操作相关知识点总结整理
python实现飞船大战
![](https://img.aspxhome.com/file/2023/3/82583_0s.gif)
在ASP中使用SQL语句之12:连接
解读python如何实现决策树算法
python3.7.3版本和django2.2.3版本是否可以兼容
![](https://img.aspxhome.com/file/2023/4/82554_0s.png)
pytorch fine-tune 预训练的模型操作
![](https://img.aspxhome.com/file/2023/2/87892_0s.png)
ASP使用xmlhttp定时触发事件
Python键鼠操作自动化库PyAutoGUI简介(小结)
![](https://img.aspxhome.com/file/2023/0/81790_0s.png)
Python中定时任务框架APScheduler的快速入门指南
python使用tkinter库实现五子棋游戏
![](https://img.aspxhome.com/file/2023/6/65026_0s.png)
DW CS4初步试用感受
![](https://img.aspxhome.com/file/uploadpic/20085/30/2008530125042602.gif)
Python之list对应元素求和的方法
利用python实现汉字转拼音的2种方法
Oracle存储过程入门学习基本语法
PHP访问MySQL查询超时处理的方法
![](https://img.aspxhome.com/file/2023/2/85812_0s.jpg)
python使用yaml 管理selenium元素的示例
![](https://img.aspxhome.com/file/2023/9/79579_0s.png)