Home > Net >  Convert image to numpy array, flip array, then turn into image
Convert image to numpy array, flip array, then turn into image

Time:09-21

I'm trying to do some python work for a class and can't get my image to flip.

import matplotlib.pyplot as plt
import numpy as np
import requests
from io import BytesIO

response = requests.get('https://www.boredpanda.com/blog/wp-content/uploads/2014/08/cat-looking-at-you-black-and-white-photography-1.jpg')
im = Image.open(BytesIO(response.content))

px = im.load()
pix_val_flat = []
for x in range(0, im.width):
    for y in range(0, im.height):
        pix_val_flat.append(px[x, y])
print(pix_val_flat)

arr = np.array(pix_val_flat)
reversed_array = arr[::-1]

#def displayImage(pix_val_flat):
#    plt.imshow(pix_val_flat)
im.show(reversed_array)

Is there a better way to do this?

CodePudding user response:

If working exclusively with images, you should consider using a dedicated library to make your life much easier.

For example, using Pillow you could do :

from PIL import Image

import numpy as np
import matplotlib.pyplot as plt 

with Image.open("whatever_image.jpg") as im:

    im = im.transpose(method=Image.FLIP_LEFT_RIGHT)
    plt.imshow( np.asarray(im) )

After making all the modifications you want to your array/image (both matrix of values in ram) , you can easily save it as a classic image format file with :

im1.save("whatever_image_modified.jpg")

However, there is a lot of other libraries that are well maintained for image processing, depending on your preferences / requirements.

To name a few :

  • Scikit-image.
  • OpenCV.
  • Mahotas.
  • SimplelTK.
  • SciPy.
  • Pillow.
  • Matplotlib.

source

CodePudding user response:

You don't necessarily need any special function to do this, it is possible just using indexing:

import numpy as np
import matplotlib.pyplot as plt

img = plt.imread("cat.jpg")
flipped_lr = img[:, ::-1, :]
flipped_ud = img[::-1, :, :]
  • Related