简体   繁体   中英

How to set pixel value of a cv::Mat1b?

I have copied a grayscale image into a cv::Mat1b , and I want to loop through each pixel and read and change its value. How can I do that?

My code looks like this :

cv::Mat1b newImg;
grayImg.copyTo(newImg);
for (int i = 0; i < grayImg.rows; i++) {
        for (int j = 0; i < grayImg.cols; j++) {
            int pixelValue = static_cast<int>(newImg.at<uchar>(i, j));
            if(pixelValue > thresh)
                newImg.at<int>(i,j) = 0;
            else
                newImg.at<int>(i, j) = 255;         
        }
    }

But in the assignments (inside of if and else ), I get the error Access violation writing location .

How do I read and write specific pixels correctly?

Thanks !

Edit

Thanks to @Miki and @Micka, this is how I solved it :

for (int i = 0; i < newImg.rows; i++) {
        for (int j = 0; j < newImg.cols; j++) {
            // read :
            cv::Scalar intensity1 = newImg.at<uchar>(i,j);
            int intensity = intensity1.val[0];
            // write :
            newImg(i, j) = 255;
    }
}
newImg.at<int>(i,j)

should be

newImg.at<uchar>(i,j) 

Because cv::Mat1b is of uchar type

i suggest :

cv::Mat1b newImg;
newImg = grayImg > thresh ;

or

cv::Mat1b newImg;
newImg = grayImg < thresh ;

also look at the OpenCV Tutorials to know how to go through each and every pixel of an image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM