简体   繁体   中英

Opencv only process the parts of image

I want to make a negative transformation for the image which is a very simple program.

But when I run the program. I want to transform all of the pixels in the image, but only 1/3 parts of that are processed. I don't make sure where is wrong. all the code I followed the book. But the result is different.

I think there is something wrong about the columns, but when I change the value of I.cols in negativeImage function with the actual value of image. the output still keep the same. only 1/3 parts of image are processed. If I 3 times the I.cols all of the pixels in the iamge could be processed.

vector<uchar> getNegativeLUT() {
vector<uchar> LUT(256, 0);
for (int i = 0; i < 256; ++i)
    LUT[i] = (uchar)(255 - i);
return LUT;
}

void negativeImage(Mat& I) {
vector<uchar> LUT = getNegativeLUT();
for (int i = 0; i < I.rows; ++i) {
    for (int j = 0; j <  I.cols; ++j) {
        I.at<uchar>(i, j) = LUT[I.at<uchar>(i, j)];
        //stack overflow
    }   
  }
}

int main() {
Mat image = imread("1.png");
Mat processed_image2 = image.clone();
negativeImage(processed_image2);
printf("%d", image.cols);

imshow("Input Image", image);
imshow("Negative Image", processed_image2);
waitKey(0);

return 0;
}

Output Image

You need to put correct type with at<> operator. Your PNG image has to be converted to 8UC1 to then use uchar type to access each pixel. I suppose your image has 3 channels, so you only iterate over 1/3 of the image. Also, I suggest you to use ptr<> operator in rows loop and then access to pixel as an array.

Mat M;
cvtColor(I, M, CV_BGR2GRAY);

// M is CV_8UC1 type
for(int i = 0; i < M.rows; i++)
{
    uchar* p  = M.ptr<uchar>(i);
    for(int j = 0; j < I.cols; j++)
    {
        p[j] = LUT[p[j]];
    }
}

EDIT: you should use cv::LUT instead of doing it yourself.

cv::Mat lut(1, 256, CV_8UC1);
for( int i = 0; i < 256; ++i) 
{
    lut.at<uchar>(0,i) = uchar(255-i);
}
cv::LUT(M, lut, result);

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