Search code examples
c++opencvnullmat

Mat cells set to NULL in OpenCV?


Quick summary:

I create a cv::Mat by

cv::Mat m = cv::Mat::zeros(MAP_HEIGHT, MAP_WIDTH, CV_8UC1)

My approach after this is to see if i have any polygons in a list of polygons, and if i do, fill them in, and lastly i assign m to my public cv::Mat map (defined in the header-file). What happens is basically:

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;

The logic of my program is that position x,y is allowed if a 0 is occupying the cell. So no polygons => all map should be 'legit'.

I have defined this method to check whether a given x-y coordinate is allowed.

bool Map::isAllowed(bool res, int x, int y) {
    unsigned char allowed = 0;
    res = (map.ptr<unsigned char>(y)[x] == allowed);
}

Now the mystery begins.

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.

If i print (c[j] == NULL) it prints 1. If i print the entire Mat i see only 0's flashing over my screen, so they are clearly there.

Why does isAllowed(bool, x, y) return false for (0,0), when there is clearly a 0 there?

Let me know if any more information is needed, thanks!


Solution

  • Problem is solved now, here are my mistakes for future reference:

    1: When printing, @Miki pointed out that unsigned characters -> ASCII value gets printed, not numerical representation.

    2: in isAllowedPosition(bool res, int x, int y), res has a primitive type. Aka this is pushed on the stack and not a reference to a memorylocation. When writing to it, i write to the local copy and not to the one passed in as an argumet.

    Two possible fixes, either pass in a pointer to a memorylocation and write to that, or simply return the result.