【问题标题】:How can I save 2D integer array to image?如何将二维整数数组保存到图像?
【发布时间】:2021-10-23 23:00:04
【问题描述】:

我看到很多问题询问如何将 2D 数组保存到图像中,大多数答案都是关于将图像保存为灰度图像。但我试图找出一种方法来保存可以实际显示每个数组单元格中的每个值的图像。有没有办法保存在python中显示数组值的图像?

【问题讨论】:

  • 您可以使用 Python Imaging Library (PIL) 的 Pillow fork 构建这样的图像。它包含一个ImageDraw模块,可以绘制线条等简单的2D图形,还包括一个名为text的函数,可以渲染字符串。
  • 那么您真正想做的是读取像素值,将这些值输出为表格,并可能将输出表格保存为新的图像文件?
  • @Guang 我不会读取图像的像素值。但我正在尝试将从我的项目生成的小型二维数组或列表保存到图像中。数组或列表的最大大小为 5*8,每个单元格的值都是整数。并希望保存的数组或列表图像将包含每个单元格的整数值
  • 请问整数的可能取值范围是多少?
  • @MarkSetchell 整数范围将是 [0, 32] 或 [-1, 32],谢谢 :)

标签: python arrays image image-processing


【解决方案1】:

我对此进行了快速尝试。你可以玩转颜色和大小。

#!/usr/local/bin/python3

from PIL import Image, ImageFont, ImageDraw
import numpy as np

# Variables that can be edited
w, h = 8, 5     # width and height of Numpy array
cs = 100        # cell side length in pixels

# Make random array but repeatable
np.random.seed(39)
arr = np.random.randint(-1,33, (h,w), np.int)

# Generate a piece of canvas and draw text on it
canvas = Image.new('RGB', (w*cs,h*cs), color='magenta')

# Get a drawing context
draw = ImageDraw.Draw(canvas)
monospace = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf", 40)

# Now write numbers onto canvas at appropriate points
for r in range(h):
   draw.line([(0,r*cs),(w*cs,r*cs)], fill='white', width=1)        # horizontal gridline
   for c in range(w):
      draw.line([(c*cs,0),(c*cs,h*cs)], fill='white', width=1)     # vertical gridline
      cx = cs // 2 + (c * cs)     # centre of cell in x-direction
      cy = cs // 2 + (r * cs)     # centre of cell in y-direction
      draw.text((cx, cy), f'{arr[r,c]}', anchor='mm', fill='white', font=monospace)

# Save
canvas.save('result.png')

【讨论】:

  • 马克:这里没有必要使用 numpy,所以 IMO 你应该把它排除在外——否则是一个很好的答案。
猜你喜欢
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 2017-09-12
相关资源
最近更新 更多