saving image using matplotlib in python

Viewed 240

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 Answers

img is a numpy array, so you can just use img / 2. It's also much faster than using a list loop.

myImg = img / 2
mpimg.imsave("foo.jpg", myImg)
Related