本文共 3026 字,大约阅读时间需要 10 分钟。
本文将展示如何利用OpenCV图像处理库对图像边界进行处理的示例代码。通过代码解析和实际操作,读者可以快速掌握OpenCV的基本操作。
#include#include #include #include using namespace std;using namespace cv;int main(){ Mat src = imread("E:\\vs2015\\opencvstudy\\1.jpg", 1); if (src.empty()) { cout << "could not load the src image!" << endl; return -1; } char *input_title = "input Image"; imshow(input_title, src); Mat dst; int top = (int)(0.05 * src.rows); int bottom = (int)(0.05 * src.rows); int left = (int)(0.05 * src.cols); int right = (int)(0.05 * src.cols); RNG rng(12345); int borderType = BORDER_DEFAULT; int c = 0; while (true) { c = waitKey(500); if ((char)c == 27) // ESC { break; } if ((char)c == 'r') // r { borderType = BORDER_REPLICATE; } else if ((char)c == 'w') // w { borderType = BORDER_WRAP; } else if ((char)c == 'c') // c { borderType = BORDER_DEFAULT; } Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); copyMakeBorder(src, dst, top, bottom, left, right, borderType, color); imshow("output image", dst); } GaussianBlur(src, dst, Size(5, 5), 0, 0, BORDER_DEFAULT); // waitKey(0); return 0;}
图像加载与初始化:
imread函数加载图像。图像显示:
imshow函数显示图像,设置窗口标题为"input Image"。边界处理设置:
BORDER_DEFAULT。用户交互与界面反馈:
waitKey函数进入事件循环,等待用户输入事件。copyMakeBorder函数复制并调整图像边界。imshow函数显示处理后的图像。高斯模糊处理:
GaussianBlur函数对图像进行高斯模糊处理。waitKey(0)保持窗口在屏幕上显示。安装OpenCV环境:
运行代码:
.cpp文件,添加相应的头文件路径。参数调整:
BORDER_REPLICATE和BORDER_WRAP)对比图像边界处理效果。效果展示:
Mat src = imread("E:\\vs2015\\opencvstudy\\1.jpg", 1);if (src.empty()){ cout << "could not load the src image!" << endl; return -1;}char *input_title = "input Image";imshow(input_title, src);Mat dst;int top = (int)(0.05 * src.rows);int bottom = (int)(0.05 * src.rows);int left = (int)(0.05 * src.cols);int right = (int)(0.05 * src.cols);RNG rng(12345);int borderType = BORDER_DEFAULT;while (true){ c = waitKey(500); if ((char)c == 27) // ESC { break; } if ((char)c == 'r') // r { borderType = BORDER_REPLICATE; } else if ((char)c == 'w') // w { borderType = BORDER_WRAP; } else if ((char)c == 'c') // c { borderType = BORDER_DEFAULT; } Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); copyMakeBorder(src, dst, top, bottom, left, right, borderType, color); imshow("output image", dst);}GaussianBlur(src, dst, Size(5, 5), 0, 0, BORDER_DEFAULT); 代码简化:
参数预定义:
异常处理:
imread函数调用时增加异常处理,确保程序稳定运行。性能优化:
注释优化:
通过本文的示例代码,读者可以快速掌握OpenCV图像处理库的基本操作。从图像加载与显示到边界处理与高斯模糊,每一步都清晰地展示了实现细节。通过实际操作与参数调整,读者可以根据需求对图像进行多样化处理。
转载地址:http://wmsfk.baihongyu.com/