PIL converting from I;16 to JPEG produce white ima

2019-07-22 17:48发布

问题:

I am having a problem converting an image I;16 to JPEG with PIL. My original image can be found here (as pickle). The original image comes from a DICOM file. Here is the code to try:

import pickle
import matplotlib.pyplot as plt
from PIL import Image

ims = pickle.load(open("pixel_array.pickle", "rb"))

img = Image.fromarray(ims)
print(img.mode)
rgb_im = img.convert("RGB")
print(rgb_im.mode)

fig, ax = plt.subplots(figsize=(20, 10))
ax.imshow(rgb_im, cmap=plt.cm.bone)
fig.show()

Unfortunately the image is completely white, while it should be a chest x-ray scan image.

I followed this other stackoverflow question, and with the following

ims = pickle.load(open("pixel_array.pickle", "rb"))

img = Image.fromarray(ims)
print(img.mode)

img.mode = 'I'
rgb_im = img.point(lambda i:i*(1./256)).convert('L')
rgb_im.save('my.jpeg')

fig, ax = plt.subplots(figsize=(20, 10))
ax.imshow(rgb_im, cmap=plt.cm.bone)
fig.show()

I am able to visualise the image, but unfortunately my.jpeg is a black image. Please help!

回答1:

Your values are 16-bit and need to be reduced to 8-bit for display. You can scale them from their current range of 2,712 (i.e. ims.min()) to 4,328 (i.e. ims.max()) with the following:

from PIL import Image
import numpy as np
import pickle

# Load image
ims = pickle.load(open("pixel_array.pickle", "rb"))

# Normalise to range 0..255
norm = (ims.astype(np.float)-ims.min())*255.0 / (ims.max()-ims.min())

# Save as 8-bit PNG
Image.fromarray(norm.astype(np.uint8)).save('result.png')