0

I want to change the images in format .nii into .png but I get this error from the function imageio.imsave:

ValueError: Max value == min value, ambiguous given dtype

Here is a part of the code:

import numpy, shutil, os, nibabel
import sys, getopt
import glob
import imageio
inputfile = 'lung_mask'
outputfile = 'lung_mask_png/'
if not os.path.exists(outputfile):
   os.makedirs(outputfile)
for inputfile in glob.glob("lung_mask/*.nii"):
    image_array = nibabel.load(inputfile).get_data()
    nx, ny, nz = image_array.shape
    total_slices = image_array.shape[2]
    print(image_array.shape)
    print(image_array.dtype)
    data = numpy.rot90(image_array[:, :, 0])
    image_name = inputfile[:-4] + ".png"
    imageio.imsave(image_name, data.astype(numpy.int16))
    shutil.move(image_name, outputfile)
Frodon
  • 3,684
  • 1
  • 16
  • 33
Amir
  • 1
  • Please provide or link to the `.nii` file in question. For some random `lung_mask/*.nii` from [this Kaggle dataset](https://www.kaggle.com/andrewmvd/covid19-ct-scans), I can't reproduce the given error. Also, please provide the full stack trace. – HansHirse Jan 25 '21 at 12:00

1 Answers1

0

The error message you are receiving states that your image data is problematic given your chosen data type.

Images that are represented as integers have to be in the range [0, 255]. This is the range of numpy.uint8, while you are using numpy.int16 in your code, here: imageio.imsave(image_name, data.astype(numpy.int16)), which has a range of [-32768, 32767]. You need to ensure that data contains only integers between 0 and 255, and then convert it to uint8: imageio.imsave(image_name, data.astype(numpy.uint8))

Disclaimer: I do not know what goes on under the hood of imageio, which makes this conversion necessary in unicolored images where data.min() == data.max(). I would assume its some sort of scaling that becomes necessary when images are in a format that allows values outside of [0,255]. Perhaps, they try to map data.min() to 0 and data.max() to 255, which doesn't work when the value is the same. But this is all conjecture.

Zakum
  • 2,157
  • 2
  • 22
  • 30