c++ - 将图像转换为占用网格
问题描述
我刚刚开始学习 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 做到这一点?
我会将该矩阵存储到一个文本文件中,但我知道该怎么做。
不要担心我要对那个矩阵做什么。我不是在问那个。
解决方案
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, ....]
推荐阅读
- javascript - 使用表单提交值调用 JS 函数
- postgresql - 如何使用 Nest 配置 docker / pgadmin
- python - 序列化器 Validate() 方法未在序列化器 DRF 中调用
- node.js - 如何在 NodeJS 中正确加密 JSON 字符串
- list - 如何创建这两个列表的所有可能组合?
- project-reactor - 获取 :: 无法初始化类 reactor.netty.http.client.HttpClientConfiguration
- android - 如何为 Agora 1 对 1 视频通话应用显示来电通知
- vue.js - allowedDate 不能用于 vuetify 上的异步或 ajax 吗?
- java - 如何在 Java 中将“2019-10-11T04:56:06.000Z”转换为时间戳?
- javascript - 在 React Native 中创建一个简单的主题标签格式化程序