python - 我应该为Python中的数组类型烦恼吗?

标签 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)

最佳答案

我已经下载了图片。得出以下结论:

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]),这就是为什么所有前景看起来都是白色的:[-2147483647, 61] 中的 [0, 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 应该完全没问题(我主要使用浮点图像)。

关于python - 我应该为Python中的数组类型烦恼吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31459645/

相关文章:

python - 在 nd 数组的一个轴上应用一维函数

Python UnitTest - 如何在无需手动编写的情况下访问子测试消息?

python - RabbitMQ 不断关闭连接

c - 我在 C 中出现段错误的原因是什么?

java - java如何给final属性赋值

python - 安装模块时出现 Odoo 错误 - XMLSyntaxError : None

javascript - ng-repeat limitTo 可以应用于在 json 而不是数组上重复吗?

c - stbi_load_from_memory 没有正确读取图像尺寸

java - 如何在 Android 中以编程方式删除图片?

c++ - 如何正确进行图像反投影?