Litwos
Litwos

Reputation: 1338

Should I bother for array type in Python?

I am trying to import a series of .tiff images in Python using the code below. I want to transform them intro arrays, so I can process the data. The problem is that, for some images that are signed integers 32 Bit, they are shown all white colour, and I don't recieve the proper matrix. What is a workaround here? Thanks.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
import numpy as np

img = mpimg.imread("filename.tif")
img_array = np.asarray(img, dtype=np.float)
plt.imshow(img_array,cmap=cm.Greys_r)
plt.show()
print(img_array)

Upvotes: 1

Views: 88

Answers (2)

Imanol Luengo
Imanol Luengo

Reputation: 15889

I've downloaded the image. Find below the conclusions:

from skimage import io
io.use_plugin('freeimage')
data = io.imread('/tmp/data.tif')

I use scikits-image for image analysis, but you can stick with matplotlib's built ins if you wish, there is no difference.

  • Some basic statistics:

    >>> print(data.dtype, data.min(), data.max(), data.shape)
    int32 -2147483647 61 (4094, 6383)
    >>> print(np.unique(data))
    [-2147483647, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
     31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
     47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61]
    >>> print(len(np.unique(data)))
    46
    
  • Trying to plot the image:

    plot(data)
    

enter image description here

So what is happening here? You have int32 data, with most of the values in the [0, 61] range, but the background of the image is hardcoded as -2147483647. That's why, when you try to plot something you see nothing but black and white. Internally, matplotlib is rescaling the grayscale range to your data (from [0, 255] to [-2147483647, 61]), and that's why all your foreground looks white: [0, 61] in [-2147483647, 61] is pretty much white.

What can you do to avoid this from happening?

1- Visualize ignoring the background (the following results are the same image with different colormaps):

    imshow(data, vmin=-1)  # <-1 values are set to -1, only for visualization

enter image description here enter image description here

2- Replace the background value in your data by some value higher or lower:

    data[data < 0] = data.max() + 1  # or data[data >= 0].min() - 1
    imshow(data)

enter image description here enter image description here

Later on you can convert your data to the type you want, and answering your original question: float should be perfectly OK (I mostly work with floating point images).

Upvotes: 2

FintanH
FintanH

Reputation: 110

What kind of values are you seeing in the image array?

I notice that you're trying to show the image with Greyscale, if I'm not mistake. I'm pretty sure that grayscale is between 0-255 so try representing the array with np.uint8

Upvotes: 1

Related Questions