Opencv(C++)笔记--像素重映射

目录

1--概念

2--Opencv API

3--实例代码


1--概念

        从图像中的一个像素点获取其像素值,并将这个像素值映射到新图像中另一个像素点位置的过程;

        为了完成整个映射过程,有时需对非整数像素位置进行插值,因为源图像和目标图像之间并不总是存在一对一的像素对应关系。

2--Opencv API

Opencv(C++)笔记--像素重映射_第1张图片

cv::remap(src, dst, map_x, map_y, cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(0, 255, 255));

3--实例代码

# include 
# include 
# include 

void update_map(cv::Mat src, cv::Mat map_x, cv:: Mat map_y, int idx){
    for(int row = 0; row < map_x.rows; row++){
        for(int col = 0; col < map_x.cols; col++){
            switch (idx){
                case 0: // 缩小
                    if (col > (map_x.cols*0.25) && col < (map_x.cols*0.75) && row > (map_x.rows*0.25) && row < (map_x.rows*0.75)){
                        map_x.at(row, col) = (float)(2 * (col - (map_x.cols*0.25) + 0.5));
                        map_y.at(row, col) = (float)(2 * (row - (map_x.rows*0.25) + 0.5));
                    }
                    else{
                        map_x.at(row, col) = 0;
                        map_y.at(row, col) = 0;
                    }
                    break;

                case 1: // 左右颠倒
                    map_x.at(row, col) = (float)(map_x.cols - col - 1);
                    map_y.at(row, col) = (float)(row);
                    break;

                case 2: // 上下颠倒
                    map_x.at(row, col) = (float)(col);
                    map_y.at(row, col) = (float)(map_x.rows - row - 1);
                    break;
                
                case 3: // 上下左右颠倒
                    map_x.at(row, col) = (float)(map_x.cols - col - 1);
                    map_y.at(row, col) = (float)(map_x.rows - row - 1);
                    break;
            }

        }
    }
}

int main(int argc, char** argv){

    cv::Mat src;
    cv::Mat map_x;
    cv::Mat map_y;
    cv::Mat dst;
    int idx;

    src = cv::imread("C:/Users/Liujinfu/Desktop/opencv_bilibili/test1.jpg");
    if (src.empty()){
        printf("could not load image..\n");
        return -1;
    }
    cv::imshow("input", src);

    map_x.create(src.size(), CV_32FC1);
    map_y.create(src.size(), CV_32FC1);
    
    int c = 0;
    while(true){
        c = cv::waitKey(10);
        if(c == 27){ // esc键
            break;
        }
        idx = c % 4;
        update_map(src, map_x, map_y, idx);
        cv::remap(src, dst, map_x, map_y, cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(0, 255, 255));
        cv::imshow("output", dst);
    }

    return 0;
}

Opencv(C++)笔记--像素重映射_第2张图片

 

你可能感兴趣的:(Opencv(C++)学习笔记,opencv,计算机视觉,人工智能)