使用OpenCV将小图块平铺到大图中

4
假设我有一个200x200像素的图像。 我想要一个800x800像素的版本,其中我基本上会复制200x200的图片并将其填充到800x800的图像中(将较小的图像掏出来放到更大的图像中)。
你如何在openCV中实现这个目标?这似乎很简单,但我不知道如何创建另一个与模式具有相同类型但大小更大(画布大小)的cv :: Mat,或者是否可以增加原始的200x200像素图像的行和列,然后简单地使用循环将其粘贴到其余部分的图像中。
顺便说一下,我正在使用的是openCV 2.3版本。我已经对具有固定尺寸的图像进行了相当多的处理,但当涉及到增加矩阵的尺寸时,我有点茫然。

你好,您是在询问将图像调整为更大的尺寸还是将小图像平铺在一起以制作更大的图像吗? - Abid Rahman K
我请求将较小的图像平铺到一个更大的(最初为空的)版本中。 - Patrick.SE
然后你从卡尔那里得到了下面的答案。 - Abid Rahman K
3个回答

1
你可以使用tile功能:
def tile_image(tile, height, width):      
  x_count = int(width / tile.shape[0]) + 1
  y_count = int(height / tile.shape[1]) + 1

  tiled = np.tile(tile, (y_count, x_count, 1))

  return tiled[0:height, 0:width]

1
你建议使用 cv::repeat,但是却展示了一个使用 np.tile 的 Python 示例,而不是 C++ 的示例... - Cris Luengo

1

在C++中,你可以像这样做:

cvx::Mat CreateLargeImage(const cvx::Mat& small, int new_rows, int new_cols) {
  // Create a Mat of the desired size, the mat may also be created by resizing of the smaller one.
  cvx::Mat result(new_rows, new_cols, 16);
  const int sm_rows = small.rows;
  const int sm_cols = small.cols;
  for (int r = 0; r < result.rows; ++r) {
    for (int c = 0; c < result.cols; ++c) {
        // use mod operation to effectively repeat the small Mat to the desired size.
        result.at<cvx::Vec3b>(r, c)[0] =
            small.at<cvx::Vec3b>(r % sm_rows, c % sm_cols)[0];
        result.at<cvx::Vec3b>(r, c)[1] =
            small.at<cvx::Vec3b>(r % sm_rows, c % sm_cols)[1];
        result.at<cvx::Vec3b>(r, c)[2] =
            small.at<cvx::Vec3b>(r % sm_rows, c % sm_cols)[2];
    }
  }
  return result;
}

或者你可以使用openCV的repeat函数。例如,

在Python中

import cv2
...
duplicated = cv2.repeat(original, 4, 4)

在C++中

 cv::Mat original= cv::imread("./benz.jpeg");
 cv::Mat duplicated;

 cv::repeat(original, 4, 4, duplicated);

更新了。谢谢你的建议! - Hui Liu

0
FYI- @karlphillip回答中的博客,基本思路是使用cvSetImageROI和cvResetImageROI。这两个都是C API。
在以后的版本中,例如v2.4和3.x,可以使用所需位置和尺寸定义一个Rect,并将所需部分称为img(rect)。
C API中的示例(函数式风格):
cvSetImageROI(new_img, cvRect(tlx, tly, width, height);
cvCopy(old_img, new_img);
cvResetImageROI(new_img);

在使用类的C++ API中:

Mat roi(new_img, Rect(tlx, tly, width, height));
roi = old_img;    // or old_img.clone()

在C++中的另一种方式(复制图像):

old_img.copyTo(new_img(Rect(tlx, tly, width, height)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接