Search code examples
pixel

Accessing pixel pointer


Can you explain to me how the accessing pixel has been done in this double loop ? how do they change rows and cols and pixel's value?

for(int i=0;i<cv_ptr->image.rows;i++)
    {   
        float* ptr_img_A = cv_ptr->image.ptr<float>(i); 

        for(int j=0;j<cv_ptr->image.cols;j++)
        {                   
            *ptr_img_B=255*(*ptr_img_A)/3.5;
             ptr_img_A++;   
        }           
    }

Thank you.


Solution

  • First of, is this the complete code or is ptr_img_B actually ptr_img_A in the first row of the inner loop?

    Secondly I would recommend naming your variables by the content it has.

    for(int i=0;i<cv_ptr->image.rows;i++)
    {   
        float* row_ptr = cv_ptr->image.ptr<float>(i); 
    
        for(int j=0;j<cv_ptr->image.cols;j++)
        {                   
            *row_ptr=255*(*row_ptr)/3.5;
             row_ptr++;   
        }           
    }
    

    So basically it scales every pixel in the image with the factor of 255/3.5

    Regarding the access of the pixel, it is stored in memory like this

          COL
    ROW   1  2  3  4
      1   0  1  2  3
      2   4  5  6  7
      3   8  9 10 11
      4  12 13 14 15
    

    Then in order to access, for example pixel on row 3, col 2

    float* row_ptr = cv_ptr->image.ptr<float>(row-1);
    float value  = row_ptr[col-1];
    

    Finally I hope you will enjoy your time with openCV, it is a really nice framework :)