我刚刚开始学习OpenCV,我想知道如何转换这样的图像:
进入占领网格,就像这样:
int grid[ROW][COL] =
{
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 }
};
1: cell is not blocked (white pixel).
0: cell is blocked (black pixel).
我不会完全使用该图片。我将使用只有墙壁的图片:没有文字,没有家具,没有窗户和没有门的符号。只有带有“洞”的墙壁才能显示门。
我想读取图像并在像素为白色时返回1,在像素为黑色时返回0。只有那样。
如何使用OpenCV做到这一点?
我会将矩阵存储到文本文件中,但是我知道该怎么做。
不用担心我将要处理该矩阵。我不是问这个。
答案 0 :(得分:2)
Mat
在OpenCV中就像您提到的网格一样。 .pgm
是机器人操作系统中用于存储“占用网格”地图的格式。任何图像格式都适合表示。
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
//read input image as gray
Mat image_gray = imread("input.jpg", CV_LOAD_IMAGE_GRAYSCALE);
// convert gray image to binary image
// After threshold, all values are either (0 or 200)
Mat imgage_bw;
cv::threshold(image_gray, imgage_bw, 200, 255.0, THRESH_BINARY);
// if you really want images with 0 for blocked cell and 1 for free cell
Mat image_grid = imgage_bw/255;
// save to disk
imwrite("output.pgm", image_grid);
//write result to text file
FileStorage file("ouput.yaml", cv::FileStorage::WRITE);
file <<"grid " <<image_grid;
file.release();
return 0;
}
ouput.yaml
%YAML:1.0
grid : !!opencv-matrix
rows: 400
cols: 800
dt: u
data: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ....]