Reputation: 63
I see lot of questions ask how to save 2D array to an image, and most of the answer is about saving image as gray scale image. But I'm trying to figure out a way to save image that can actually display each value in each cell of array. Is there a way save image that display value of array in python?
Upvotes: 1
Views: 562
Reputation: 207395
I has a quick try at this. You can play around with colours and sizes.
#!/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')
Upvotes: 2