opencv學習(三十一)之圖像邊緣像素填充估計copyMakeBorder()

前面講到圖像卷積運算的時候涉及到對圖像邊緣像素的估計,這裏講介紹圖像邊緣像素進行卷積運算。大部分opencv中的函數是將原圖像複製到一個比原圖像尺寸更大的圖像中然後實現邊緣的自動填充。這種方式得到的像素點可以執行卷積操作。下面介紹兩種方式:
- 1.BORDER_CONSTANT:使用一個常數填充像素邊緣
- 2.BORDER_REPLICATE:將圖像中邊緣的行和列像素值直接填充像素邊緣
opencv提供了copyMakeBorder()函數實現對圖像邊緣像素填充的功能,其函數原型如下:

void cv::copyMakeBorder  ( InputArray  src,  
  OutputArray  dst,  
  int  top,  
  int  bottom,  
  int  left,  
  int  right,  
  int  borderType,  
  const Scalar &  value = Scalar()  
 )  

參數解釋:

  • InputArray: 輸入圖像
  • OutputArray: 輸出圖像
  • int top/bottom/left/right四個參數指定原圖像由每個方向上向外插入的像素個數,例如:top=1, bottom=1, left=1, right=1意味着圖像向外擴充一個像素。
  • int borderType: 邊緣類型,可以通過borderInterpolate()查看詳細信息。
  • const Scalar & value = Scalar():當像素填充類型爲BORDER_CONSTANT時填充的像素值。
    其示例代碼如下:
/*程序說明
 *當按下按鍵‘c’代表使用BORDER_CONSTANT
 *RNG生成的隨機數作爲像素值進行填充
 *當按下按鍵‘r’代表使用BORDER_REPLICATE
 *圖像擴充的邊框由原圖像邊緣像素的值進行填充
 */

#include <opencv2/imgproc.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;
using namespace cv;

//聲明全局變量
Mat srcImage, dstImage;
int g_top, g_bottom, g_left, g_right;
int borderType;
Scalar value;
String windowName = "copyMakeBorder Demo";
RNG rng(12345);

int main()
{
    int c;

    srcImage = imread("dog.jpg");

    //判斷圖像是否加載成功
    if(srcImage.empty())
    {
        cout << "圖像加載失敗!" << endl;
        return -1;
    }
    else
        cout << "圖像記載成功" << endl << endl;
    imshow("原圖像", srcImage);

    //程序使用說明
    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(windowName, WINDOW_AUTOSIZE);

    //初始化邊框參數
    g_top = (int)(0.05*srcImage.rows);
    g_bottom = (int)(0.05*srcImage.rows);
    g_left = (int)(0.05*srcImage.cols);
    g_right = (int)(0.05*srcImage.cols);

    //顯示初始圖像
    dstImage = srcImage;    
    imshow(windowName, dstImage);

    while(true)
    {
        c = waitKey(500);

        if((char)c == 27)   //c爲ESC程序退出
        {break;}
        else if((char)c == 'c')
        {borderType = BORDER_CONSTANT;}
        else if((char)c == 'r')
        {borderType = BORDER_REPLICATE;}

        value = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
        copyMakeBorder(srcImage, dstImage, g_top, g_bottom, g_left, g_right, borderType, value);

        imshow(windowName, dstImage);
    }

    return 0;
}

運行結果如下:
這裏寫圖片描述
這裏寫圖片描述

發佈了98 篇原創文章 · 獲贊 630 · 訪問量 123萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章