把输入图像中各个像素按照一定的规则映射到另外一张图像的对应位置上去,形成一张新的图像。
如下图,包括图片的缩放和反转也可以通过像素映射实现。
Remap(
InputArray src,// 输入图像
OutputArray dst,// 输出图像
InputArray map1,// x 映射表 (仅支持CV_32FC1/CV_32FC2的图片类型)
InputArray map2,// y 映射表
int interpolation,// 选择的插值方法,常见线性插值,可选择立方等
int borderMode,// BORDER_CONSTANT
const Scalar borderValue// color
)
如下代码:
remap(src, dst, map_x, map_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 255, 255));
子以下子函数中,case0为图像缩小一般的映射表,case1为Y方向对调,case2为X方向对调,case3为XY方向对调。
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)+0.5);//为什么要乘以2?因为括号内部只有原图的一半
map_y.at<float>(row, col) = 2 * (row - (src.rows*0.25)+0.5);//为什么需要+0.5,因为实际宽度为(col+1)
}
else {
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);//实际上是(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;
}
}
}
}
#include
#include
#include
using namespace cv;
Mat src, dst, map_x, map_y;
const char* OUTPUT_TITLE = "remap demo";
int index = 0;
void update_map(void);
int main(int argc, char** argv) {
src = imread("D:/fruit.jpg");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
char input_win[] = "input image";
namedWindow(input_win, WINDOW_AUTOSIZE);
namedWindow(OUTPUT_TITLE, WINDOW_AUTOSIZE);
imshow(input_win, src);
map_x.create(src.size(), CV_32FC1);
map_y.create(src.size(), CV_32FC1);
int c = 0;
while (true)
{
c = waitKey(500);
if ((char)c == 24)
{
break;
}
index = c % 4;
update_map();
remap(src, dst, map_x, map_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 255, 255));
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)+0.5);//为什么要乘以2?因为括号内部只有原图的一半
map_y.at<float>(row, col) = 2 * (row - (src.rows*0.25)+0.5);//为什么需要+0.5,因为实际宽度为(col+1)
}
else {
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);//实际上是(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;
}
}
}
}