Python 画正方形,写数字的代码如下:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
WIDTH = 100 * 4
HEIGHT = 100 * 4
image = Image.new('RGB', (WIDTH, HEIGHT), (255, 255, 255))
colors = ['red', 'green', 'blue']
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("C:/Windows/Fonts/consola.ttf", 32, encoding="unic")
d = [
{'x1': 1, 'y1': 1, 'x2': 40, 'y2': 40, 'number': 1},
{'x1': 41, 'y1': 41, 'x2': 80, 'y2': 80, 'number': 2},
{'x1': 81, 'y1': 81, 'x2': 120, 'y2': 120, 'number': 3}
]
for o in d:
draw.rectangle(( o['x1'], o['y1'], o['x2'], o['y2']), colors[o['number'] - 1], 'black')
draw.text((o['x1'], o['y1']), str(o['number']), 'white', font)
image.save('code.jpg', 'jpeg')
结合你的图,你需要先计算出每个正方形的左上顶点坐标和右下顶点坐标,再把其中的数字对应到一种颜色。
以上代码稍稍加上顶点计算就可以用了,如果需要字体居中,可以加上一个偏移,偏移的计算方法为两顶点坐标之和的一半减去字体大小的一半。