3

I'm trying to make a simple code that loads an image, divide the value of each pixel by 2 and stores the image. The image is stored in an array [1280][720][3]. After changing the value of each pixel I've chequed that the values are the expected. For some reason the values are correct but when I store the new image and check it, the values of the pixels are not the same as before... The image is 1280x720 pixels and each pixel has 3 bytes (one for each color rgb)

import matplotlib.image as mpimg

img = mpimg.imread('image.jpg')   # (1280, 720, 3)

myImg = []

for row in img:
    myRow = []
    for pixel in row:
        myPixel = []
        for color in pixel:
            myPixel.append(color // 2)
        myRow.append(myPixel)
    myImg.append(myRow)


mpimg.imsave("foo.jpg", myImg)
1
  • You have to remember that JPEG is a lossy format, when you save it the compression algorithm might change values slightly. If the result on file is approximately the values you saved, then your code is working as expected. If you need the exact values you set, use a non-lossy image format. Commented Apr 15, 2021 at 18:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.