Take the 2-minute tour ×

How can I draw regular grid lines over a tiff image? I want to draw regular square grids for each interval (say 100 by 100 pixels) over the image and save that with the drawings. I also need to overlay each grid id as '1','2',...at the middle of each grid box.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

You will need the python imaging library (PIL) installed. (See here https://pypi.python.org/pypi/PIL). See these answers for examples of ways to install PIL: answer 1, answer 2

Right, with that installed, the following code should do what you ask for:

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

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

# Set up figure

# Remove whitespace from around the image

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

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

# Add the image

# Find number of gridsquares in x and y direction

# Add some labels to the gridsquares
for j in range(ny):
    for i in range(nx):

# Save the figure

Which, if used on the grace_hopper.png example file, produces the following output:

Image with numbered grid

share|improve this answer

This can be done effectively in two lines by looping over the image data at your grid intervals. Using the canonical image from the SIPI database as an example

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

enter image description here

The answer by @tom may be more robust as it works with the matplotlib library. I'll leave this example up for its simplicity.

share|improve this answer

Your Answer


