為了完成卷積后圖像大小不變,原始圖像需要進行邊界填充
copyMakeBorder(src,dst,top,bottom,left,right,bordertype,value);
bordertype:
BORDER_DEFAULT 填充黑色
BORDER_CONSTANT 用指定像素填充邊界
BORDER_REPLICATE 用一只邊緣像素填充邊緣像素
BORDER_WARP 用另一邊像素來補償填充
#include"pch.h" #include<iostream> #include<opencv2/opencv.hpp> using namespace std; using namespace cv; int main(int argc, char**argv) { Mat src, dst; src = imread("b.jpg"); if (src.empty()) { cout << "Load img failed" << endl; return -1; } imshow("input img", src); int top = (int)(src.rows*0.05); int bottom = (int)(src.rows*0.05); int left = (int)(src.cols*0.05); int right = (int)(src.cols*0.05); 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') { borderType = BORDER_REPLICATE; } else if ((char)c == 'w') { borderType = BORDER_WRAP; } else if ((char)c == 'c') { borderType = BORDER_CONSTANT; } else { 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", dst); } waitKey(0); return 0; }