opencv平均值池化

1.源碼實現

#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

/*平均值池化*/

int main()
{
    Mat srcImage = imread("3.jpg");
    int width, height;
    int n = 9;
    int r, g, b;

    width = srcImage.cols;
    height = srcImage.rows;

    Mat dstImage(width, height, CV_8UC3);

    //遍歷所有像素, 並設置像素值
    for(int i=0; i<height/n; i++)
    {
        for(int j=0; j<width/n; j++)
        {
            r = 0;
            g = 0;
            b = 0;

            for(int u=0; u<n; u++)
            {
                for(int v=0; v<n; v++)
                {
                    b += srcImage.at<Vec3b>(n*i+u, n*j+v)[0];
                    g += srcImage.at<Vec3b>(n*i+u, n*j+v)[1];
                    r += srcImage.at<Vec3b>(n*i+u, n*j+v)[2];
                }
            }

            for(int u=0; u<n; u++)
            {
                for(int v=0; v<n; v++)
                {
                    dstImage.at<Vec3b>(n*i+u,n*j+v)[0] = saturate_cast<uchar>(b / (n*n));
                    dstImage.at<Vec3b>(n*i+u,n*j+v)[1] = saturate_cast<uchar>(g / (n*n));
                    dstImage.at<Vec3b>(n*i+u,n*j+v)[2] = saturate_cast<uchar>(r / (n*n));
                }
            }
        }
    }

    imwrite("mean_pooling.jpg", dstImage);

    return 0;
}

2.編譯源碼

$ g++ -o test test.cpp -std=c++11 -I/usr/local/include -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -Wl,-rpath=/usr/local/lib

3.運行結果


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章