如何将二维整数数组保存到图像?

How can I save 2D integer array to image?

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

我有一个快速尝试。您可以尝试使用颜色和尺寸。

#!/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')