Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading