【问题标题】:Python - Inverting a .tif binary imagePython - 反转 .tif 二进制图像
【发布时间】:2020-04-10 01:33:26
【问题描述】:

我正在使用带有 Jupyter Notebook 3 的 Google Colab。

我需要反转 .tif 二进制图像,将其变为 0 并将其变为 0。

我该怎么做? (我仍然需要将图像保留为 .tif)

编辑:我认为我的图像被读取就好像它们完全由 0 组成。有没有办法正确读取图像?

编辑 2: 这是链接:https://drive.google.com/open?id=1cVqE6DpU_8AhShzX9_MvJpdlTBEAsMMT

编辑 3: 它由 0 和 1 组成,当我尝试在 QGis 上对其进行可视化时,它完美显示。 代码如下:

import numpy as np
import imageio

image = imageio.imread("path")

for i in range(0, len(image)):
  for x in range(0, len(image)):
    if image[i,x] == 0:
      image[i,x] = 1
    elif image[i,x] == 1:
      image[i,x] = 0

imageio.imwrite("path", image)

【问题讨论】:

  • 如果你分享你的图片链接,我会看看。
  • 谢谢马克,我已经用链接编辑了我的问题。

标签: python-3.x image-processing google-colaboratory tiff


【解决方案1】:

使用包imageio

使用imread函数读取图片

反转ndarray

imwrite保存图片

https://imageio.readthedocs.io/en/stable/userapi.html

【讨论】:

  • 我不知道如何使它工作,我认为我的图像被读取就好像它们完全由 0 组成。有没有正确读取图像的方法?
【解决方案2】:

你好像在用imageio,你可以试试:

import imageio
import numpy as np                                                                          

# Load image
image = imageio.imread("mask.tif")                                                         

# Change 1s to 0s and 0s to 1s
image = 1 - image                                                                           

# Save result
imageio.imwrite("result.tif", image)

请注意,您应该尽量避免使用 Python 图像处理的 for 循环,因为它们非常缓慢且效率低下。当您使用 imageio 时,您的图像已经是一个 Numpy 数组,因此您可以将整个求逆作为一个简单的向量化数学进行,无需循环和 if 语句 - 这也很慢。


如果你使用 PIL/Pillow,你可以像这样转换 1 到 0 和 0 到 1:

from PIL import Image

# Open image
im = Image.open('mask.tif') 

# Invert
result = im.point(lambda i: 1-i) 

# Save
result.save('result.tif')


关于您的图像...它有一个 8 位数据通道。 60% 的像素为 0,40% 的像素为 1。如果显示它会显得很暗,因为 0 是黑色,255 是白色,所以你的图像是黑色和 99.5% 的黑色而不是黑白。

【讨论】:

  • 这在我的机器上工作得很好,谢谢!我不知道为什么,但它在 Google Colab 上不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 2010-12-05
  • 2011-02-28
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
相关资源
最近更新 更多