[Python] Why is cv2.imencode('jpg', ...) seemingly changing the color of an image?

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    I create and view a random image. Then, this image is encoded as a jpg file with opencv. However, after decoding this image the colors have been changed slightly. This behavior is not seen using png to encode. Can anyone explain why this occurs? Is it a negative result of the jpeg compression? Am I doing something wrong? Code sample below to recreate this.

    import cv2
    import numpy as np

    random_image = np.random.randint(255, size=(4,4,3), dtype=np.uint8)
    cv2.imshow('Image', random_image)
    cv2.waitKey()

    _, img_encoded = cv2.imencode('.jpg', random_image)
    img_string = img_encoded.tostring()
    npimg = np.fromstring(img_string, dtype=np.uint8)
    img = cv2.imdecode(npimg, 1)
    cv2.imshow('Image', img)
    cv2.waitKey()

    # Does not happen with png
    _, img_encoded = cv2.imencode('.png', random_image)
    img_string = img_encoded.tostring()
    npimg = np.fromstring(img_string, dtype=np.uint8)
    img = cv2.imdecode(npimg, 1)
    cv2.imshow('Image', img)
    cv2.waitKey()



    Edited to add some 4x4 images.

    Original:

    [​IMG]

    JPG

    [​IMG]

    PNG

    [​IMG]

    Edited again with 512x512 images

    Original 512x512

    JPG 512x512

    PNG 512x512

    Continue reading...

Compartilhe esta Página