opencv学习-像素重映射
Posted 殇堼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了opencv学习-像素重映射相关的知识,希望对你有一定的参考价值。
API-remap
remap(src, dst, map_x, map_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 255));
单个案例代码-向X轴做对称
#include<opencv2\\opencv.hpp>
#include <iostream>
using namespace cv;
int main()
{
Mat src, dst;
Mat map_x, map_y;
src = imread("D:/images/lena.png");
if (src.empty())
{
printf("读取文件错误,请确定目录下是否有imread函数~!\\n");
return -1;
}
imshow("【原图】", src);
//创建效果图,x重映射图,y重映射图
dst.create(src.size(), src.type());
map_x.create(src.size(), CV_32FC1);
map_y.create(src.size(), CV_32FC1);
//双层循环,遍历每一个像素点,改变map_x,map_y的值
for (int j = 0; j < src.rows; j++)
{
for (int i = 0; i < src.cols; i++)
{
map_x.at<float>(j, i) = static_cast<float>(i);//横坐标保持不变
map_y.at<float>(j, i) = static_cast<float>(src.rows - j);//纵坐标取反
}
}
//进行重映射
remap(src, dst, map_x, map_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 255));
//显示效果图
imshow("【程序窗口】", dst);
waitKey();
return 0;
}
代码展示
#define INPUT_TITLE "input image"
#define OUTPUT_TITLE "remap image"
#include<iostream>
#include<opencv2\\opencv.hpp>
using namespace std;
using namespace cv;
Mat img, src;//img 输入图像 ; src 最终输出的图像
Mat map_x, map_y;
int index = 0;
void updata_map();
int main() {
img = imread("D:/images/lena.png");
if (!img.data)
{
cout << "ERROR : could not load image.";
return -1;
}
namedWindow(INPUT_TITLE, WINDOW_AUTOSIZE);
namedWindow(OUTPUT_TITLE, WINDOW_AUTOSIZE);
imshow(INPUT_TITLE, img);
//建立映射表
map_x.create(img.size(), CV_32FC1);
map_y.create(img.size(), CV_32FC1);
int c = 0;
while (true)
{
c = waitKey(500);
index = c % 4;
if ((char)c == 27)
{
break;
}
updata_map();
remap(img, src, map_x, map_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 255));
imshow(OUTPUT_TITLE, src);
}
return 0;
}
void updata_map() {
for (int row = 0; row < img.rows; row++)
{
for (int col = 0; col < img.cols; col++)
{
switch (index)
{
//index = 0 ,图像的行跟列为为原来的1/2。
//index = 1,为左右翻转(列变换,行不变)
//index = 2,为上下翻转(行变换,列不变)
//index = 3,为中心旋转
case 0:
if (col >(img.cols*0.25) && col<(img.cols*0.75) && row>(img.rows*0.25) && row < (img.rows*0.75)) {
map_x.at<float>(row, col) = 2 * (col - (img.cols*0.25));
map_y.at<float>(row, col) = 2 * (row - (img.rows*0.25) - 0.25);
}
else
{
map_x.at<float>(row, col) = 0;
map_y.at<float>(row, col) = 0;
}
break;
case 1:
map_x.at<float>(row, col) = (img.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) = (img.rows - row - 1);
break;
case 3:
map_x.at<float>(row, col) = (img.cols - col - 1);
map_y.at<float>(row, col) = (img.rows - row - 1);
break;
default:
break;
}
}
}
}
以上是关于opencv学习-像素重映射的主要内容,如果未能解决你的问题,请参考以下文章