在矩阵中添加数字作为图像的简便方法?

时间:2015-03-26 18:59:03

标签: python numpy

我正在创建一个棋盘图案,如下所示:

def CheckeredBoard( x=10 , y=10 , sq=2 , xmax = None , ymax = None ):
    coords = np.ogrid[0:x , 0:y]
    idx = (coords[0] // sq + coords[1] // sq) % 2 
    if xmax != None: idx[xmax:] = 0.
    if ymax != None: idx[:, ymax:] = 0.
    return idx
ch = CheckeredBoard( 100, 110 , 10 )
plt.imshow2( ch )

我想要的是在一些方框中添加一个数字来编号,这样当我运行plt.imshow2( ch )时,我会将数字作为图像的一部分。

我能想到这样做的唯一方法是使用某种注释,然后保存图像并加载带注释的图像,但这看起来非常麻烦。

例如,成功的矩阵看起来像:

1 1 1 1 0 0 0 0
1 1 0 1 0 0 0 0
1 0 0 1 0 0 0 0
1 1 0 1 0 0 0 0
1 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0
1 1 1 1 0 0 0 0
0 0 0 0 1 1 1 1
0 0 0 0 1 1 0 1
0 0 0 0 1 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0
0 0 0 0 1 1 0 1
0 0 0 0 1 1 1 1

上面的矩阵在两个角上有1和8。 enter image description here 感谢任何帮助,如果您需要其他信息,请与我们联系。

由于

修改

这更接近我最终想要的结果。

加入红色圆圈以强调。

enter image description here

2 个答案:

答案 0 :(得分:0)

这样的事情怎么样?

n = 8
board = [[(i+j)%2 for i in range(n)] for j in range(n)]


from matplotlib import pyplot
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)


ax.imshow(board, interpolation="nearest")

from random import randint

for _ in range(10):
  i = randint(0, n-1)
  j = randint(0, n-1)
  number = randint(0,9)

  ax.annotate(str(number), xy=(i,j), color="white")


pyplot.show()

enter image description here

显然,您将拥有自己的方式来查找数字,并选择它们,除此之外,注释功能还包含您需要的所有内容。

您可能需要偏移数字,在这种情况下,您可以只设置一个大小并计算出需要多少偏移它们,或者您可以计算出方块的边界框并将它们偏移如果你想要的话。

为数字着色你也有几个选项 - 你可以选择标准颜色,或者你可以对它们进行着色;

for _ in range(10):
  i = randint(0, n-1)
  j = randint(0, n-1)
  number = randint(0,9)

  colour = "red"
  if (i+j)%2 == 1:
    colour = "blue"

  ax.annotate(str(number), xy=(i,j), color=colour)

enter image description here

但老实说,我认为白色选项更具可读性。

答案 1 :(得分:0)

使用PIL / Pillow怎么样?

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

#-- your data array
xs = np.zeros((20,20))

#-- prepare the text drawing
img = Image.fromarray(xs)
d = ImageDraw.Draw(img)
d.text( (2,2), "4", fill=255)

#-- back to array
ys = np.asarray(img)

#-- just show
pylab.imshow(ys)