具體代碼以下:ios
#include <opencv2/opencv.hpp> #include <iostream> #include <math.h> using namespace cv; Mat src, dst, map_x, map_y; const char* OUTPUT_TITLE = "remap demo"; int index = 0; //輸入默認爲0 void update_map(void); //申明函數 int main(int argc, char** argv) { src = imread("L:/5.jpg"); if (!src.data) { printf("could not load image...\n"); return -1; } char input_win[] = "input image"; namedWindow(input_win, CV_WINDOW_AUTOSIZE); namedWindow(OUTPUT_TITLE, CV_WINDOW_AUTOSIZE); imshow(input_win, src); map_x.create(src.size(), CV_32FC1); //定義map_x.size大小併爲浮點型 map_y.create(src.size(), CV_32FC1); //每500ms循環檢查輸入更新一次 int c = 0; while (true) { c = waitKey(500); if ((char)c == 27) { //若輸入爲Esc則退出 break; } index = c % 4; //對輸入數值模4取餘運算 update_map(); //call update_map()函數 remap(src, dst, map_x, map_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 255)); //remap函數參數:1.輸入圖像 2.輸出圖像 34.映射表x,y 5.插值方式 6.默認 7. 顏色 imshow(OUTPUT_TITLE, dst); } return 0; } void update_map(void) { for (int row = 0; row < src.rows; row++) { for (int col = 0; col < src.cols; col++) { switch (index) { case 0: //將原圖像縮小一半,後映射到圖像中心 if (col >(src.cols * 0.25) && col <= (src.cols*0.75) && row >(src.rows*0.25) && row <= (src.rows*0.75)) { map_x.at<float>(row, col) = 2 * (col - (src.cols*0.25)); map_y.at<float>(row, col) = 2 * (row - (src.rows*0.25)); } else { //邊緣部分0像素填充 map_x.at<float>(row, col) = 0; map_y.at<float>(row, col) = 0; } break; case 1://上下顛倒 map_x.at<float>(row, col) = (src.cols - col - 1); map_y.at<float>(row, col) = row; break; case 2: //左右鏡像 map_x.at<float>(row, col) = col; map_y.at<float>(row, col) = (src.rows - row - 1); break; case 3://上下左右顛倒 map_x.at<float>(row, col) = (src.cols - col - 1); map_y.at<float>(row, col) = (src.rows - row - 1); break; } } } }
結果:函數
按下0spa
按下1:3d
按下2:code
按下3:blog