opencv remap pixel remapping

The input to the remap() function is a source image and a mapping matrix. The mapping matrix contains new coordinates for each pixel, specifying the position of each pixel in the output image.

Suppose the coordinates of a pixel in the original image are ( x , y ) (x,y)(x,y ) , its new coordinates in the output image are( x ′ , y ′ ) (x',y')(x,y' ). To compute( x ′ , y ′ ) (x',y')(x,y ), we need to define a mapping functionf ( x , y ) = ( x ′ , y ′ ) f(x,y)=(x',y')f(x,y)=(x,y ), the original coordinates( x , y ) (x,y)(x,y ) is mapped to new coordinates( x ′ , y ′ ) (x',y')(x,y)

In the remap() function, the mapping matrix consists of two grid matrices mapx map_xmapx m a p y map_y mapycomposition, each grid matrix has the same size as the original image. mapx map_xmapx m a p y map_y mapyEach element ( i , j ) in (i,j)(i,j ) contains the pixel( i , j ) (i,j)(i,j ) new coordinates( x ′ , y ′ ) (x',y')(x,y)

Therefore, we can put the mapping function f ( x , y ) f(x,y)f(x,y)表示为 f ( x , y ) = ( m a p x [ i , j ] , m a p y [ i , j ] ) f(x,y)=(map_x[i,j],map_y[i,j]) f(x,y)=(mapx[i,j],mapy[i,j ]) , where( i , j ) (i,j)(i,j ) is the pixel ( x , y ) in the original image(x,y)(x,y ) coordinates.

In the implementation of the cv2.remap() function, the cv2.meshgrid() function is used to create the grid matrix mapx map_xmapx m a p y map_y mapy, while the mapping function f ( x , y ) f(x,y)f(x,y ) to calculate the new coordinates( x ′ , y ′ ) (x',y')(x,y)

#include <random>
#include <iostream>
#include "opencv2/opencv.hpp"

void salt(cv::Mat image,int n){
    
    
   //随机数生成器
   std::default_random_engine generator;
   std::uniform_int_distribution<int> randomRow(0,image.rows-1);
   std::uniform_int_distribution<int> randomCol(0,image.cols-1);

   int i,j;
   for(int k = 0; k<n;k++){
    
    
       //随机生成图形位置
       i = randomCol(generator);
       j = randomRow(generator);
       if(image.type() == CV_8UC1){
    
     //灰度图像
         image.at<uchar>(j,i) = 0;
       }else if(image.type() == CV_8UC3){
    
    
           image.at<cv::Vec3b>(j,i)[0] = 0;
           image.at<cv::Vec3b>(j,i)[1] = 0;
           image.at<cv::Vec3b>(j,i)[2] = 0;
       }
   }
}


void wave(const cv::Mat &image,cv::Mat &result){
    
    
   //映射参数
   cv::Mat srcX(image.rows,image.cols,CV_32F);
   cv::Mat srcY(image.rows,image.cols,CV_32F);
   //创建映射参数
   for(int i=0;i<image.rows;i++){
    
    
       for(int j=0;j<image.cols;j++){
    
    
           srcX.at<float>(i,j) =  float(image.cols - j - 1);;
           srcY.at<float>(i,j) = i;

       }
   }
   cv::remap(image,result,srcX,srcY,cv::INTER_LINEAR);
}



int main(){
    
    


   cv::Mat a = cv::imread("../../a.png",1);

   cv::Mat result_a;

   wave(a,result_a);

   cv::imshow("image",a);

   cv::imshow("image_remap",result_a);

   cv::waitKey(0);

   return 0;
}


Please add a picture description

Guess you like

Origin blog.csdn.net/m0_49302377/article/details/130600823