Mat 单元格在 OpenCV 中设置为 NULL?
Mat cells set to NULL in OpenCV?
快速总结:
我通过
创建了一个 cv::Mat
cv::Mat m = cv::Mat::zeros(MAP_HEIGHT, MAP_WIDTH, CV_8UC1)
此后我的方法是查看多边形列表中是否有任何多边形,如果有,请填写它们,最后我将 m 分配给我的 public cv::Mat 地图(在头文件中定义)。
发生的事情基本上是:
cv::Mat m = cv::Mat::zeros(MAP_HEIGHT, MAP_WIDTH, CV_8UC1);
// possibly fill polygons with 1's. Nothing happens if there are no polygons
map = m;
我程序的逻辑是,如果单元格中有 0,则允许位置 x,y。所以没有多边形 => 所有地图都应该是 'legit'.
我已经定义了这个方法来检查是否允许给定的 x-y 坐标。
bool Map::isAllowed(bool res, int x, int y) {
unsigned char allowed = 0;
res = (map.ptr<unsigned char>(y)[x] == allowed);
}
现在谜团开始了。
cout << cv::countNonZero(map) << endl; // prints 0, meaning all cells are 0
for(int i = 0; i < MAP_HEIGHT; i++) {
unsigned char* c = map.ptr<unsigned char>(i);
for(int j = 0; j < MAP_WIDTH; j++) {
cout << c[j] << endl;
}
} // will print nothing, only outputs empty lines, followed by a newline.
如果我打印 (c[j] == NULL) 它会打印 1。
如果我打印整个垫子,我只看到 0 在我的屏幕上闪烁,所以它们很明显。
为什么 isAllowed(bool, x, y) return 对于 (0,0) 是错误的,而那里显然有一个 0?
如果需要更多信息,请告诉我,谢谢!
由于您的数据类型是 uchar
(又名 unsigned char
),因此您打印的是 ASCII 值。使用
cout << int(c[j]) << endl;
打印实际值。
另外 map.ptr<unsigned char>(y)[x]
可以简单地重写为 map.at<uchar>(y,x)
,或者如果您使用 Mat1b
为 map(y,x)
问题已经解决,以下是我的错误供以后参考:
1: 打印时,@Miki 指出打印的是无符号字符 -> ASCII 值,而不是数字表示。
2:在isAllowedPosition(bool res, int x, int y)中,res是原始类型。也就是将其压入堆栈而不是对内存位置的引用。写入时,我写入本地副本而不是作为参数传入的副本。
两个可能的修复,要么传入一个指向内存位置的指针并写入该位置,要么只是 return 结果。
快速总结:
我通过
创建了一个 cv::Matcv::Mat m = cv::Mat::zeros(MAP_HEIGHT, MAP_WIDTH, CV_8UC1)
此后我的方法是查看多边形列表中是否有任何多边形,如果有,请填写它们,最后我将 m 分配给我的 public cv::Mat 地图(在头文件中定义)。 发生的事情基本上是:
cv::Mat m = cv::Mat::zeros(MAP_HEIGHT, MAP_WIDTH, CV_8UC1);
// possibly fill polygons with 1's. Nothing happens if there are no polygons
map = m;
我程序的逻辑是,如果单元格中有 0,则允许位置 x,y。所以没有多边形 => 所有地图都应该是 'legit'.
我已经定义了这个方法来检查是否允许给定的 x-y 坐标。
bool Map::isAllowed(bool res, int x, int y) {
unsigned char allowed = 0;
res = (map.ptr<unsigned char>(y)[x] == allowed);
}
现在谜团开始了。
cout << cv::countNonZero(map) << endl; // prints 0, meaning all cells are 0
for(int i = 0; i < MAP_HEIGHT; i++) {
unsigned char* c = map.ptr<unsigned char>(i);
for(int j = 0; j < MAP_WIDTH; j++) {
cout << c[j] << endl;
}
} // will print nothing, only outputs empty lines, followed by a newline.
如果我打印 (c[j] == NULL) 它会打印 1。 如果我打印整个垫子,我只看到 0 在我的屏幕上闪烁,所以它们很明显。
为什么 isAllowed(bool, x, y) return 对于 (0,0) 是错误的,而那里显然有一个 0?
如果需要更多信息,请告诉我,谢谢!
由于您的数据类型是 uchar
(又名 unsigned char
),因此您打印的是 ASCII 值。使用
cout << int(c[j]) << endl;
打印实际值。
另外 map.ptr<unsigned char>(y)[x]
可以简单地重写为 map.at<uchar>(y,x)
,或者如果您使用 Mat1b
为 map(y,x)
问题已经解决,以下是我的错误供以后参考:
1: 打印时,@Miki 指出打印的是无符号字符 -> ASCII 值,而不是数字表示。
2:在isAllowedPosition(bool res, int x, int y)中,res是原始类型。也就是将其压入堆栈而不是对内存位置的引用。写入时,我写入本地副本而不是作为参数传入的副本。
两个可能的修复,要么传入一个指向内存位置的指针并写入该位置,要么只是 return 结果。