pythonpython-imaging-library

Error when converting image to array and back to image in python, image is erased. How do I get circle back, not a straight line?


When I run this code, from original image (blue ring attached), at first show I see circle but after if I convert to RGB and do any manipulation(I tried selecting different columns, etc.), I always get a straight line (hopefully attached here too). Eventually I would like to be able to manipulate RGB channels, but for now just display every color channel as same matrix as original blue channel.

[input image, which first displayed][1]

enter image description here

Code is:

from PIL import Image
import numpy as np

img = Image.open(r"test.jpg") # creating image object
img1 = img.convert("RGB") # using convert method for img1
img1.show()


def magColBlue(x):
    x=np.array(x)
    print("x first shape is ", np.shape(x))
    x=x[:,:,0]
    print("x 2nd shape is ", np.shape(x))
    print(x)
    return x



blueAmount =magColBlue(img1)
print("blue shape",np.shape(blueAmount))
imgBlue = Image.fromarray(np.asarray([blueAmount,blueAmount,blueAmount]), 'RGB')
imgBlue.show()

Solution

  • I believe the issue lies in the following line:

    Image.fromarray(np.asarray([blueAmount,blueAmount,blueAmount])
    

    The numpy array you use here would have shape (3, x, y) rather than (x, y, 3) which may have been your intention.