【问题标题】:Image to 0,1 text图像到 0,1 文本
【发布时间】:2019-08-05 14:35:51
【问题描述】:

我需要将图像转换为仅由 0 和 1 组成的文本或图像。有没有办法以编程方式执行此操作,最好是在 Python 上?

这是我的尝试:

第一步:打开图片:

from PIL import Image
srcImage = Image.open("src.jpg")

第 2 步: 灰度图像:

grayImage = srcImage.convert('L')

第三步:二值化图片:

binarizedImage = grayImage.point(lambda x: 0 if x<128 else 255, '1')

现在,我坚持将黑点转换为 1,将白点转换为 0,并将其保存到文本文件中,图像高度转换为行(在本例中:174 像素到 174 行),图像宽度转换为文本长度(在这个例子中:310 像素到 310 个字符长度)或更大的图像,用 0 代替白点,用 1 代替黑点。

对这两种情况的解决方案将不胜感激。

完整的二值化代码(binarizing的PIL方式的修改版):

from PIL import Image
srcImage = Image.open("src.jpg")
grayImage = srcImage.convert('L')
binarizedImage = grayImage.point(lambda x: 0 if x<128 else 255, '1')
binarizedImage.save("binarized.png")

【问题讨论】:

  • 您可以使用numpy.array(image) 将图像从PIL.Image 转换为numpy.array,然后使用apply_over_axes 应用您的lambda(如果要将其重新转换为图像,here's a nice way to do it )(如果这对你有帮助,我可以从这条评论中回复帖子)
  • 谢谢,我会检查这个以确保它是否有效。如果您将其发布为答案,我会很高兴,以便我可以接受,以便其他人更容易找到类似情况的解决方案。

标签: python image text binary python-imaging-library


【解决方案1】:

您可以为此使用 numpy 库

from PIL import Image
from scipy.ndimage import zoom
import numpy as np
srcImage = Image.open("src.jpg")
grayImage = col.convert('L')
array = np.array(grayImage)
array = zoom(array, 310/174)
np.savetxt("binarized.txt", array<128, fmt="%d")

np.array 将 PIL Image 转换为 numpy 数组格式,以给定的比例缩放插值数组,array &lt; 128 创建二进制数组,fmt="%d" 设置结果将保存为整数

【讨论】:

  • 如果他想要图像而不是.txt,您可以添加Image.fromarray() 解决方案
  • 但是获取二值图像的方法有问题。
  • +1,它可以工作,但是白点表示为 1,而黑色表示为 0。无论如何我都可以补充它们。那么第二部分 - 将图像保存为更大的 0 和 1 图像呢?
  • 我忘了插值。我编辑了响应并添加了这个陡峭的。您应该提供有效的标量。也将array &gt; 128 反转为array &lt; 128(Im not sure if you need <=)
  • 非常感谢,现在不用补了。 :)
猜你喜欢
  • 1970-01-01
  • 2012-10-26
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 2012-04-20
  • 2020-04-07
  • 2014-12-31
相关资源
最近更新 更多