在matplotlib中的图像上绘制网格线

时间:2013-12-04 06:19:28

标签: matplotlib matplotlib-basemap

如何在tiff图像上绘制规则的网格线? 我想在图像上为每个间隔(比如说100 x 100像素)绘制规则的正方形网格,并将其与图纸一起保存。我还需要在每个网格框的中间将每个网格ID覆盖为“1”,“2”,...。

3 个答案:

答案 0 :(得分:18)

您需要安装python映像库(PIL)。 (见https://pypi.python.org/pypi/PIL)。有关安装PIL的方法示例,请参阅以下答案:answer 1answer 2

是的,安装完成后,以下代码应该按照您的要求执行:

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
try:
    from PIL import Image
except ImportError:
    import Image

# Open image file
image = Image.open('myImage.tiff')
my_dpi=300.

# Set up figure
fig=plt.figure(figsize=(float(image.size[0])/my_dpi,float(image.size[1])/my_dpi),dpi=my_dpi)
ax=fig.add_subplot(111)

# Remove whitespace from around the image
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)

# Set the gridding interval: here we use the major tick interval
myInterval=100.
loc = plticker.MultipleLocator(base=myInterval)
ax.xaxis.set_major_locator(loc)
ax.yaxis.set_major_locator(loc)

# Add the grid
ax.grid(which='major', axis='both', linestyle='-')

# Add the image
ax.imshow(image)

# Find number of gridsquares in x and y direction
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)))

# Add some labels to the gridsquares
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='w',ha='center',va='center')

# Save the figure
fig.savefig('myImageGrid.tiff',dpi=my_dpi)

如果在grace_hopper.png示例文件中使用,则生成以下输出:

Image with numbered grid

答案 1 :(得分:10)

通过以网格间隔循环显示图像数据,可以在两行中有效地完成此操作。以SIPI数据库中的canonical image为例

import pylab as plt

# Load the image
img = plt.imread("lena512color.tiff")

# Grid lines at these intervals (in pixels)
# dx and dy can be different
dx, dy = 100,100

# Custom (rgb) grid color
grid_color = [0,0,0]

# Modify the image to include the grid
img[:,::dy,:] = grid_color
img[::dx,:,:] = grid_color

# Show the result
plt.imshow(img)
plt.show()

enter image description here

@tom的答案可能更强大,因为它与matplotlib库一起使用。我会因为它的简单而留下这个例子。

答案 2 :(得分:0)

让我把它放在这里

def draw_grid(image, line_space=20):
    H, W = image.shape
    image[0:H:line_space] = 1
    image[:, 0:W:line_space] = 1