首页 > 解决方案 > 将图像转换为占用网格

问题描述

我刚刚开始学习 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 做到这一点?

我会将该矩阵存储到一个文本文件中,但我知道该怎么做。

不要担心我要对那个矩阵做什么。我不是在问那个。

标签: c++opencv

解决方案


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;
}

输出.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, ....]

推荐阅读