-
邊緣問題存在的原因:
前面在圖像的模糊進行中我們已經接觸到由于其在邊緣及四周由于某一方位的像素缺失,因而我們不能進行完全的卷積操作
-
OpenCV中處理邊緣的方法:
在卷積開始之前增加邊緣像素,填充的像素值為0或者RGB黑色,比如3×3在四周各填充一個邊緣的像素,OpenCV中預設的處理方法是:BORDER_DEFAULT-是通過填充最近的像素值來實作的,此外還有以下幾種處理方法
BORDER_CONSTANT:填充邊緣用指定像素值即用常數來填充
BORDER_REPLICATE:填充邊緣像素用已知的邊緣像素值,即相當于一個內插補點問題,我們也可以了解為複制最近的一行或一列像素并一直延伸至添加邊緣的寬度或高度。
BORDER_WRAP:用另外一邊的像素來補償填充,相當于一條路走不通了換另一條
- 用到的重要函數:給圖像添加邊緣的API-copyMakeBorder
void copyMakeBorder(InputArray src, OutputArray dst, int top, int bottom, int left, int right, int borderType, const Scalar& value = Scalar() );
參數分析:top、bottom、left、right分别表示邊緣的長度
borderType表示選擇的何種類型的邊緣處理方法
最後一個參數為如果選擇BORDER_CONSTANT處理方法時用以填充邊界的元素的顔色
- 實驗代碼即内容:
#include<opencv2\opencv.hpp> #include<iostream> #include<math.h> using namespace std; using namespace cv; int main() { Mat src, dst; src = imread("H:/opencv_images/test.jpg"); if (src.empty()) { cout << "could not load the images" << endl; return -1; } namedWindow("original_images", CV_WINDOW_AUTOSIZE); imshow("original_images", src); 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); int bordershape = BORDER_DEFAULT; int c = 0; RNG rng(123456); while (1) { c = waitKey(500); if ((char)c == 27)break; else if ((char)c == 'r')bordershape = BORDER_REFLECT; else if ((char)c == 'c')bordershape = BORDER_CONSTANT; else if ((char)c == 'w')bordershape = BORDER_WRAP; else bordershape = BORDER_DEFAULT; Scalar color(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); copyMakeBorder(src, dst, top, bottom, left, right, bordershape, color); namedWindow("test_images", CV_WINDOW_AUTOSIZE); imshow("test_images", dst); } waitKey(0); destroyAllWindows(); return 0; }