Abhishek V. Pai
Abhishek V. Pai

Reputation: 351

Drawing,numbering and Identifying grid cells in opencv

I have a code which I use to draw gridlines over an image and print the cell number. But I have a couple of problems. the code is

    int stepSize = 65;
    int k=1;
    char s;

    int width = src.size().width;
    int height = src.size().height;

    for (int i = 0; i<height; i += stepSize)
        cv::line(src, Point(0, i), Point(width, i), cv::Scalar(0, 255, 255));

    for (int i = 0; i<width; i += stepSize)
        cv::line(src, Point(i, 0), Point(i, height), cv::Scalar(255, 0, 255));

    for (int i = 0; i < width; i += stepSize)
    {
        for (int j = 0; j < height; j += stepSize)
        {
            sprintf(&s, "%d", k);
            putText(src, &s, Point2f(i, j), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255, 255));
        }
        k++;

    }

where src is

enter image description here

after drawing the grids, I get

enter image description here

A you can see,the variable k that I use to print the number of the grid cell,initialises to zero each time we move to the next row. That is one problem. The next one is I would like to perform grid selection.That is,instead of printing a number inside the cell I want to assign that number to that grid cell,so that I can perform various functions in that particular grid using that number as the cell's identity.For example, I would like to use mouse click to choose grid cell or print out the identity number of that grid.

Upvotes: 0

Views: 1866

Answers (1)

max66
max66

Reputation: 66190

For your first problem, I'm not sure to understand your desiderata but, if you want numbering in this way

  1  2  3  4  5  6  7  8
  9 10 11 12 13 14 15 16
 17 ...

you should

  1. switch height/width cycles

  2. and increment k in the inner cycle

Something like

for (int j = 0; j < height; j += stepSize)
   for (int i = 0; i < width; i += stepSize)
    {
        sprintf(&s, "%d", k++);
        putText(src, &s, Point2f(i, j), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255, 255));
    }

If you can use C++11, following the Miki's suggestion, simply

for (int j = 0; j < height; j += stepSize)
   for (int i = 0; i < width; i += stepSize)
        putText(src, std::to_string(k++), Point2f(i, j), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255, 255));

For your second problem... I'm not sure what you want but I suppose that the following function (that give you the index of a point of posX and posY coordinates) should help (I hope so)

int getCellId (int posX, int posY, int width, int height, int stepSize)
 {
   int numCols ( width / stepSize + ( width % stepSize ? 1 : 0 ) );
   int col ( posX / stepSize );
   int row ( posY / stepSize );

   return row * numCols + col + 1;
 }

Note the +1 in return; it's because you start with k=1.

Upvotes: 2

Related Questions