0

I'm currently trying to write a function that inverts an image using ImageIO and no loops but I'm having a hard time. This is the code I have so far:

def inverted_color(img):
    img = imageio.imread(img)
    print(img.shape)
    img = img.astype('float32')
    img = 255 - img

Any help is appreciated!

Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73
ppboi
  • 13
  • 4
  • Can you please describe in detail (please [edit](https://stackoverflow.com/posts/66407864/edit) your question), what your actual error is? Why are you converting to `np.float32`? Since you're inverting by using `255 - img`, I assume, `img` is of type `np.uint8`!? Do you probably save the image (as JPG, PNG), and get an all black image or something like this? Then, it's very likely due to the format conversion. – HansHirse Mar 01 '21 at 08:08

2 Answers2

0

I am not sure what problem you are facing but you are almost done.

Just use:

imageio.imwrite(*'path_to_file'*,img)

to store the image in a new file/replace the old image and return it.

  • I'm not passing my testcases because it says one of my array values is returning as off by one? AKA I'm not returning the correct shape on the image. – ppboi Feb 28 '21 at 18:34
  • What is the format of you input image? Also, I think you wanted to go with `uint8`. Read about numpy datatypes [here](https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.uint8). – FugitiveMemories Mar 01 '21 at 17:36
0

Your code works fine after some additions.

import imageio
import matplotlib.pyplot as plt

img_path = './image_134.jpg'

def inverted_color(img_path):
    img = imageio.imread(img_path)
    print("org dtype", img.shape, img.dtype)
    #img = img.astype('float32') # its ok but get float32 image
    img = 255 - img
    print("inv dtype", img.shape, img.dtype)
    return img
    

img_org = imageio.imread(img_path)
img_inv = inverted_color(img_path)

imageio.imwrite("inv_img.jpg", img_inv)

plt.figure(figsize=(10,10))
plt.subplot(121)
plt.title("org")
plt.imshow(img_org, cmap='gray')
plt.subplot(122)
plt.title("inv")
plt.imshow(img_inv, cmap='gray')
plt.show()

enter image description here enter image description here

vscv
  • 86
  • 4