0

I am wanting to draw grid lines over an image in order to create squares over the image. I used the code in this answer to create the grid lines, like so:

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('test.jpg')
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='r',ha='center',va='center')

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

enter image description here

However, I am now wondering how I can change the square size to be 1cm2 each. I tried changing the gridding interval 'myInterval' to different values which does change the square size and the overall number of squares. But how do I set each square area = 1 cm squared?

Thanks :)

sums22
  • 1,793
  • 3
  • 13
  • 25
  • 1
    You need to know how many pixel make an cm. So if you are looking at it on a screen oder print it. What the dpi is and then calculate the right value for `myInterval`. Since you have 300 dpi it should be 300/2.54 dots per centimeter. that should be your `myInterval` – Tom S Jun 28 '21 at 11:54
  • Thanks @TomS . So from your comment I gather that setting myInterval=my_dpi/2.54 will set the ticks to be 1 cm apart, and therefore the squares will be 1 cm squared? – sums22 Jun 28 '21 at 14:09
  • I haven't taken a look at the underlying functions, but that is how I understand the code you posted. – Tom S Jun 28 '21 at 14:19

0 Answers0