the pixel values changed while using imwrite to jpg files in c++

Advertisements

I’m writing a code like this in c++:
I wish to have a 100% same copy image of test1.jpg.
Unfortunately, I find lots of pixel values change after cv::imwrite.

int main()
{
    cv::Mat img1 = cv::imread("./test1.jpg");
    cv::imwrite("test2.jpg", img1);
    cv::Mat img2 = cv::imread("./test2.jpg");
    int count = 0;
    for (int i = 0; i < 250; i++) {
        for (int j = 0; j < 250; j++) {
            
                if (img1.at<uchar>(i, j) != img2.at<uchar>(i, j)) {
                    count++;
                
            }
        }
    }
    std::cout << count << std::endl;
    return 0;
}

I use count in this program to see how many differences are there between these two images,
although both images (test1.jpg and test2.jpg) have the same size at 46kb, the count’s value is as high as 16768!

Is there any method to avoid the change of pixel? I’m only going to use jpg files in the program.
Thanks a lot!

>Solution :

If you want non-lossy compression, you can’t use jpg’s and have to use a .png (there’s .bmp as well but its uncompressed)

jpg = cv.imread("../resources/fisheye/1_1.jpg")
cv.imwrite("1_1.png", jpg)
png = cv.imread("1_1.png")
np.sum(np.where(jpg != png, 1, 0)) # number of differing pixels between images

Output: 0

Leave a ReplyCancel reply