0
votes

I am attempting to loop through a cv::Mat image's pixels using this code

for (int i = 0; i < src.rows;i++)
{
    for (int j = 0; j < src.cols;j++)
    {
        int temp2=IMAGE.at<uchar>(i,j)+b;

        if (temp2<0)
        {
            IMAGE.at<uchar>(i,j) = 0;
        }
        else if  (temp2>255)
        {
            IMAGE.at<uchar>(i,j) = 255;
        }
        else 
        {
            IMAGE.at<uchar>(i,j) = temp2;
        }

    }
}

The issue is when i show the IMAGE it only adjusts the pixel values for about 1/4 of the image, so it seems like it is not looping through each pixel. Is there a better way to loop through each pixel using the row/col?

1
This seems to reinvent saturated addition of a scalar to a Mat. Why not just just the existing, optimized implementation OpenCV provides? - Dan MaĊĦek

1 Answers

0
votes

Looping through with row/col should work, but it seems that the image you are trying to process has a pixel size of 4 bytes while your code assumes it is 1 byte (uchar). This would explain why you are adjusting only 1/4 of the image. You could try using cv::Vec4b instead of uchar, our perhaps CV_32SC1 (int). Both of these have a pixel size of 4 bytes instead of 1. You would use cv::Vec4b if the image pixels specify red, green, blue, alpha and CV_32SC1 would be used for 32 bit grayscale.

Examples:

// RGBA
cv::Vev4b temp2 = IMAGE.at<cv::Vec4b>(i,j);
temp2[0] += b;
temp2[1] += b;
temp2[2] += b;

or

// 32 Bit Grayscale
int temp2 = IMAGE.at<int>(i,j) + b;