简体   繁体   中英

CV2 changes the image

I have a following code:

import cv2 as cv
import numpy as np

im = cv.imread('outline.png', cv.IMREAD_UNCHANGED)
cv.imwrite('output.png', im)


f1 = open('outline.png', 'rb')
f2 = open('output.png', 'rb')

img1_b = b64encode(f1.read())
img2_b = b64encode(f2.read())

print(img1_b)
print(img2_b)

What is the reason that img1_b and img2_b are different? img2_b is much longer - why?.

I do not want to copy the file - I would like to process it before saving but this part of code is not included.

Both outline.png and output.png looks same after the operation.

What can I change in my code to make img2_b value same as img1_b??

I have tried PIL Image with same result.

The phenomenon you have run into is the result of data compression not being 100% rigidly defined. PNG files use DEFLATE compression, which requires a given compressed file must always decompress to the same output, but does not require that a given input must produce the same compressed file. This gives room for improvement in the compression algorithm where a more optimal compression may be found over a different type of file. It sounds like your original image was compressed using a better (or just different) algorithm than cv2 is using. In order to duplicate the exact compressed version you'll likely need the exact same implementation of compression algorithm that was used to create the original image.

If you want to ensure that the images are indeed identical, you should compare the decoded pixel values. In the name of not re-inventing the wheel, I'll refer you to this excellent blog post on the subject.

Edit: linked article wasn't loading consistently for me so I copied the code here for referencing.

import cv2
import numpy as np

original = cv2.imread("imaoriginal_golden_bridge.jpg")
duplicate = cv2.imread("images/duplicate.jpg")

# 1) Check if 2 images are equals
if original.shape == duplicate.shape:
    print("The images have same size and channels")
    difference = cv2.subtract(original, duplicate)
    b, g, r = cv2.split(difference)
    if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
        print("The images are completely Equal")

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