将图像转换成占据网格

4
我刚开始学习OpenCV,想知道如何将这样一张图片转换为:

enter image description here

转换成占用栅格,就像这个:

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实现?
我将把该矩阵存储到文本文件中,但我知道如何做到这一点。
不要担心我要用这个矩阵做什么。我没有问那个。

1
提供的图像和网格有任何关联吗?在任何人开始考虑解决您实际(编程?)问题之前,您必须指定如何从图像中获取网格中的“0”和“1”值。 - HansHirse
1
首先,将您的图像作为网格进行采样,然后基本实现是,如果网格方块完全是白色的,则不会被阻挡。 - chris
1
我不理解这个问题。如果图像仅包含黑白像素,那么问题在哪里?读取图像后,其中已经有了零和非零值。将非零转换为一,就完成了。 - geza
1个回答

3

OpenCV中的Mat类似于您提到的网格。 .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, ....]

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