0

I have a collection of grayscale images in a NumPy array. I want to convert the images to RGB before feeding them into a CNN (I am using transfer learning). But when I try to convert the images to RGB, almost all information in the image is lost! I have tried several libraries, but all of them lead to (almost) the same result:

Original Image:

import matplotlib.pyplot as plt
plt.imshow(X[0])

enter image description here

Using cv2:

import cv2

img = X[0].astype('float32') #cv2 needs float32 or uint8 for handling images
rgb_image = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)
plt.imshow(rgb_image)

enter image description here

img = X[0].astype('uint8') #cv2 needs float32 or uint8 for handling images
rgb_image = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)
plt.imshow(rgb_image)

enter image description here

Using PIL

from PIL import Image

img = Image.fromarray(X[0])
img_rgb = img.convert("RGB")
plt.imshow(img_rgb)

enter image description here

Using NumPy

from here: https://stackoverflow.com/a/40119878/14420572

stacked_img = np.stack((X[0],)*3, axis=-1)
plt.imshow(stacked_img)

enter image description here

What should I do to make sure the images are converted without quality loss?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Aryagm
  • 530
  • 1
  • 7
  • 18

1 Answers1

1

Correct me if I am wrong but I suspect the values in X[0] are in the range 0,255. In

img = X[0].astype('float32') #cv2 needs float32 or uint8 for handling images
rgb_image = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)
plt.imshow(rgb_image)

try replacing the first line with.

img = X[0]/255

This makes the values not only float32 but also between 0 and 1.

Lukas S
  • 3,212
  • 2
  • 13
  • 25
  • Thanks! Actually, the images were loaded from dicom files so, each image had a different range. I was able to display them properly by doing this: `img = X[0].astype('float32')/np.max(X[0])`. Now I need to find a way to put all the images in a similar range so that my CNN can actually learn something – Aryagm Aug 09 '21 at 18:37
  • @AryaMan My gut says that you're making images without a really light spot brighter. If I were you I would read about the format and avoid using information about the particular image to convert it. – Lukas S Aug 09 '21 at 18:51
  • Thanks for the feedback! I am currently looking into it, I have loaded the images from a dicom file so I am looking for a way to read the images with values between 0-255 as default. – Aryagm Aug 09 '21 at 18:58
  • Use function rescale_intensity as described here: https://stackoverflow.com/a/68513088/5239109 – ffsedd Aug 13 '21 at 14:50