如何设置cv :: Mat1b的像素值?

时间:2015-10-18 19:43:21

标签: c++ opencv

我已将灰度图像复制到cv::Mat1b,我想遍历每个像素并读取并更改其值。我怎么能这样做?

我的代码如下所示:

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;         
        }
    }

但是在分配中(ifelse内),我收到错误Access violation writing location

如何正确读取和写入特定像素?

谢谢!

修改

感谢@Miki和@Micka,我就是这样解决的:

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;
    }
}

2 个答案:

答案 0 :(得分:0)

newImg.at<int>(i,j)

应该是

newImg.at<uchar>(i,j) 

因为cv :: Mat1b属于uchar类型

答案 1 :(得分:0)

我建议:

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

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

还要查看OpenCV Tutorials以了解如何浏览图片的每个像素