我应该在Python中使用数组类型吗?

时间:2015-07-16 16:24:36

标签: python arrays image

我正在尝试使用下面的代码在Python中导入一系列.tiff图像。我想转换它们的介绍数组,所以我可以处理数据。问题是,对于一些有符号整数32位的图像,它们显示为全白色,并且我没有收到正确的矩阵。 这里的解决方法是什么? 感谢。

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)

2 个答案:

答案 0 :(得分:2)

我已经下载了图片。在下面找出结论:

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

我使用scikits-image进行图像分析,但如果您愿意,可以坚持使用matplotlib的内置插件,没有区别。

  • 一些基本统计数据:

    >>> 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
    
  • 尝试绘制图像:

    plot(data)
    

enter image description here

那么这里发生了什么?您有int32数据,大多数值都在[0, 61]范围内,但图像的背景硬编码为-2147483647。这就是为什么,当你试图绘制一些你只看到黑色和白色的东西时。在内部,matplotlib会重新调整数据的灰度范围(从[0, 255][-2147483647, 61]),这就是为什么所有前景看起来都是白色的[0, 61] [-2147483647, 61]非常白。

你可以做些什么来避免这种情况发生?

1-可视化忽略背景(以下结果是使用不同颜色图的相同图像):

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

enter image description here enter image description here

2-将数据中的背景值替换为更高或更低的某个值:

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

enter image description here enter image description here

稍后您可以将数据转换为所需类型,并回答原始问题:float应该完全正常(我主要处理浮点图像)。

答案 1 :(得分:1)

您在图像阵列中看到了什么样的值?

如果我没有弄错的话,我注意到您正试图用Greyscale显示图像。我非常确定灰度在0到255之间,所以尝试用np.uint8表示数组