Home > Back-end >  Unable to save an image after an array
Unable to save an image after an array

Time:01-29

I got this Error :

Traceback (most recent call last): File "/home/runner/Image-Loader/venv/lib/python3.8/site-packages/PIL/Image.py", line 2992, in fromarray mode, rawmode = _fromarray_typemap[typekey] KeyError: ((1, 1, 5), '|u1')

Here is my code :

img = Image.open(f"IMG/{thumb[0]}_{thumb[1]}x{thumb[1]}.png")

height,width = img.size
lum_img = Image.new('L', [height,width] , 0)

draw = ImageDraw.Draw(lum_img)
draw.pieslice([(0,0), (height,width)], 0, 360, fill = 255, outline = "white")
img_arr =np.array(img)
lum_img_arr =np.array(lum_img)
final_img_arr = np.dstack((img_arr,lum_img_arr))


im = Image.fromarray(final_img_arr)
im.save("filename.png")

I want a script who open an image and I want to crop in circle the image like they do here : https://www.geeksforgeeks.org/cropping-an-image-in-a-circular-way-using-python/. But when I want to save my Image, I got the error. Can someone help me please ?

CodePudding user response:

The pixel format of img is RGBA and not RGB.

Replace Image.open(f"IMG/{thumb[0]}_{thumb[1]}x{thumb[1]}.png") with:

Image.open(f"IMG/{thumb[0]}_{thumb[1]}x{thumb[1]}.png").convert('RGB')

Because pixel format is RGBA, there are 4 color channels instead of 3 (the A channel applies "Alpha" transparency channel).

The result of final_img_arr = np.dstack((img_arr,lum_img_arr)) is 5 "color channels" instead of 4 channels, and 5 channels is does not apply a valid image format.

We my verify that the number of channels is valid by printing the shape of final_img_arr before saving: print(final_img_arr.shape)
Make sure that the shape is (height, width, 4)

CodePudding user response:

Your code would work if you would use .jpg images instead of .png images. One cause is because the shape of the .png array is of incompatible form for the Image.fromarray(final_img_arr) calculation. You either need to save your images as .jpg before hand or find a different way to transform .png final_img_array back into an image.

png shape: final_img_array->(329, 212, 5)

jpg shape: final_img_array -> (329, 212, 4)

this could work to reshape your .png into an compatible shape:

im = Image.fromarray(final_img_arr[:,:,[0,1,2,4]])

using final_img_arr[:,:,[0,1,2,4]] will keep all the cells (pixels in your pictures) but cut out the column[3] out of every cell. This column usually contains transparency information. This means your pictures will be exactly the same except if they have for example a transparent background.

  • Related