Plot over an image background in python [duplicate]

Just like in the MATLAB example that you linked to, you have to specify the desired extent of the image when you call in imshow.

By default, matplotlib and MATLAB both place the upper left corner of the image the origin, go down and to the right from there, and set each pixel as a 1×1 square in coordinate space. This is what your image is doing.

You can control this with the extent parameter which takes the form of a list [left, right, bottom, top].

Not using extent looks like this:

import matplotlib.pyplot as plt
img = plt.imread("airlines.jpg")
fig, ax = plt.subplots()
ax.imshow(img)

enter image description here

You can see that we have a 1600 x 1200 of Samuel L. Jackson getting, quite frankly, rather annoyed with the snake aboard his airline flight.

But if we want to plot a line ranging from 0 to 300 in both dimension over this, we can do just that:

fig, ax = plt.subplots()
x = range(300)
ax.imshow(img, extent=[0, 400, 0, 300])
ax.plot(x, x, '--', linewidth=5, color="firebrick")

enter image description here

I don’t know if the line will help Mr. Jackson with his snake problem. At the very least, it won’t make things any harder.

Leave a Comment