在固定的正方形区域上绘制图像的网格线。

15 浏览
0 Comments

在固定的正方形区域上绘制图像的网格线。

我想在一张图像上绘制网格线,以创建图像上的方块。我使用了这个答案中的代码来创建网格线,如下所示:\n

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
try:
    from PIL import Image
except ImportError:
    import Image
# 打开图像文件
image = Image.open('test.jpg')
my_dpi=300.
# 设置图形
fig=plt.figure(figsize=(float(image.size[0])/my_dpi,float(image.size[1])/my_dpi),dpi=my_dpi)
ax=fig.add_subplot(111)
# 移除图像周围的空白
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
# 设置网格间距:这里使用主要刻度间距
myInterval=100.
loc = plticker.MultipleLocator(base=myInterval)
ax.xaxis.set_major_locator(loc)
ax.yaxis.set_major_locator(loc)
# 添加网格线
ax.grid(which='major', axis='both', linestyle='-')
# 添加图像
ax.imshow(image)
# 计算 x 和 y 方向上的方块数量
nx=abs(int(float(ax.get_xlim()[1]-ax.get_xlim()[0])/float(myInterval)))
ny=abs(int(float(ax.get_ylim()[1]-ax.get_ylim()[0])/float(myInterval)))
# 向方块添加一些标签
for j in range(ny):
    y=myInterval/2+j*myInterval
    for i in range(nx):
        x=myInterval/2.+float(i)*myInterval
        ax.text(x,y,'{:d}'.format(i+j*nx),color='r',ha='center',va='center')
# 保存图形
fig.savefig('myImageGrid.tiff',dpi=my_dpi)

\n\"enter\n然而,我现在想知道如何将每个方块的大小设置为1平方厘米。我尝试将网格间距 \'myInterval\' 更改为不同的值,这确实改变了方块的大小和总方块数量。但是如何设置每个方块的面积= 1 平方厘米呢?\n谢谢 🙂

0