Home > Back-end >  Why PIL.Image saves black or grayscale image?
Why PIL.Image saves black or grayscale image?

Time:12-16

I am working on a BMP file. I need to save a resized, smaller version of this file. But the PIL. Image does save grayscale image. I want to save colorful image. How can I solve it? This is a part of my code

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from PIL import ImageFile

ibmp = Image.open('E:/Project files/label1.bmp') 
width, height = ibmp.size
imgNEW = ibmp.resize((round(width/200), round(height/200)))
ImgArray = np.asarray(imgNEW)           #Array of uint8
image=Image.fromarray(ImgArray)
image_rgb=image.convert('RGB')       # Mode:RGB
image_rgb.save("E:/Project files/Outout/image_rgb.png")
#Imagenew=(image*255).astype(np.uint8)
#Imagenew.save("E:/Project files/Outout//Imagenew.tif")
plt.imshow(image_rgb)

By using these codes, could not save an image in color. But, if I want to show it, it is in color. Here you can see the output! It should be in other colors.

output

CodePudding user response:

small_im is not defined but if you can use image_rgb = cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from PIL import ImageFile
import cv2
ibmp = Image.open('./1 no.jpeg')
width, height = ibmp.size
imgNEW = ibmp.resize((round(width/200), round(height/200)))
ImgArray = np.asarray(imgNEW)  # Array of uint8
image = Image.fromarray(ImgArray)    
plt.imsave("./image_rgb.png", image,cmap='gray')
plt.imshow(image)

CodePudding user response:

I think I must be missing some aspect of your question. Let's start with this 500x500 image:

enter image description here

Then load it, reduce its size and save:

from PIL import Image

im = Image.open('image.png').resize((80,80)).save('result.bmp')

Output

enter image description here


Quick example with libvips. Starting with a 20000x20000 image, reduce to 2500x2500:

vipsthumbnail input.bmp -s 2500 -o small.jpg --vips-leak
memory: high-water mark 212.85 MB

So that only needed 212MB of RAM.

  • Related