理論
在本教程中,我們將簡(jiǎn)要介紹兩種為圖像定義額外填充(邊框)的方法:
代碼
程序的運(yùn)行流程
1.常量值邊框:為整個(gè)邊框應(yīng)用常量值的填充。 該值將每0.5秒隨機(jī)更新一次。
2.復(fù)制邊框:將從原始圖像邊緣的像素值復(fù)制邊框。
原始代碼
#include "opencv2/imgproc/imgproc.hpp"#include "opencv2/imgcodecs.hpp"#include "opencv2/highgui/highgui.hpp"#include <stdlib.h>#include <stdio.h>using namespace cv;Mat src, dst;int top, bottom, left, right;int borderType;const char* window_name = "copyMakeBorder Demo";RNG rng(12345);int main( int, char** argv ){ int c; src = imread( argv[1] ); if( src.empty() ) { printf(" No data entered, please enter the path to an image file /n"); return -1; } printf( "/n /t copyMakeBorder Demo: /n" ); printf( "/t -------------------- /n" ); printf( " ** Press 'c' to set the border to a random constant value /n"); printf( " ** Press 'r' to set the border to be replicated /n"); printf( " ** Press 'ESC' to exit the program /n"); namedWindow( window_name, WINDOW_AUTOSIZE ); top = (int) (0.05*src.rows); bottom = (int) (0.05*src.rows); left = (int) (0.05*src.cols); right = (int) (0.05*src.cols); dst = src; imshow( window_name, dst ); for(;;) { c = waitKey(500); if( (char)c == 27 ) { break; } else if( (char)c == 'c' ) { borderType = BORDER_CONSTANT; } else if( (char)c == 'r' ) { borderType = BORDER_REPLICATE; } Scalar value( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) ); copyMakeBorder( src, dst, top, bottom, left, right, borderType, value ); imshow( window_name, dst ); } return 0;}解釋
首先,我們聲明我們將要使用的變量:
我們加載源圖像src:
我們創(chuàng)建了一個(gè)窗口:
現(xiàn)在我們初始化定義邊框大小(頂部,底部,左側(cè)和右側(cè))的參數(shù)。 我們給它們的值是src大小的5%。
程序開始一個(gè)while循環(huán)。 如果用戶按下'c'或'r',則borderType變量分別取值BORDER_CONSTANT或BORDER_REPLICATE:
在每次迭代中(0.5秒后),更新變量值
我們調(diào)用函數(shù)cv :: copyMakeBorder來(lái)應(yīng)用相應(yīng)的填充:
參數(shù)介紹:
src:源圖像
dst:目標(biāo)圖像
top,bottom,left,right:圖像兩側(cè)邊框的長(zhǎng)度(以像素為單位)。 我們將它們定義為圖像原始大小的5%。
borderType:定義應(yīng)用的邊框類型。 對(duì)于此示例,它可以是常量或復(fù)制。
value:如果borderType為BORDER_CONSTANT,則這是用于填充邊框像素的值。
我們?cè)谙惹皠?chuàng)建的圖像中顯示輸出圖像
效果
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答