OpenCV之九宫格图像

         将一张图像均等分成九份,然后将这九个小块按一定间隔(九宫格效果)拷贝到新画布上。效果如下图所示:

OpenCV之九宫格图像_第1张图片

 源码:

#include
#include
using namespace std;
using namespace cv;

int main()
{
	Mat src = imread("test.jpg");
	if (src.empty())
	{
		cout << "No Image!" << endl;
		system("pause");
		return -1;
	}

	//原图宽高
	int width = src.cols;
	int height = src.rows;

	int num = 3;//小方块数量(可实现任意等份分割)

	//制作九宫格每个小方块宽高
	int step_x = width / num;
	int step_y = height / num;

	//重新resize图片尺寸
	resize(src, src, Size(step_x * num, step_y * num), 1, 1, INTER_LINEAR);

	int space = 5; //空白间隔(实现九宫格效果)

	Mat canvas = Mat(Size(src.cols + space * (num-1), src.rows + space * (num - 1)), CV_8UC3, Scalar(255,255,255)); //画布,用来制作九宫格图片

	//就图片分成9个小块,将每一小块抠图至画布
	for (int i = 0; i < num; i++)
	{
		for (int j = 0; j < num; j++)
		{
			//小方块相对于原图左上角起点
			int x = j * step_x;
			int y = i * step_y;
			//将小方块抠图至画布。其中,每扣一小块需跳过space空白
			src(Rect(x, y, step_x, step_y)).copyTo(canvas(Rect(x + space * j, y + space * i, step_x, step_y)));

			//rectangle(src, Rect(x, y, step_x, step_y), Scalar(0, 255, 0), 2);
		}
	}

	imshow("canvas", canvas);
	imshow("test", src);
	waitKey(0);
	system("pause");
	return 0;
}

你可能感兴趣的:(OpenCV,opencv,人工智能,计算机视觉)