I have read every SO thread I could find on this topic, and have read the documentation rather extensively, and even copied and pasted code from these questions/tutorials. But I am still unable to load a jpg, annotate it, and save the figure with matplotlib. I really could use some advice on this topic.
Here is an example of one of my many attempts:
import cv2
import matplotlib.pyplot as plt
image = cv2.imread(...filepath-to-img...)
fig, ax = plt.subplots()
ax.imshow(image)
ax.add_patch(plt.Rectangle(...params...)
plt.savefig(...filepath...)
The image loads correctly, and when I work interactively and run the plt.subplots( and ax.imshow(image) commands, I see a plot with the image pop up, and I get a note saying that it is an AxesImage object.
But when I got to save, it says 'Figure size 432x288 with 0 Axes,' and the resulting image saved to disk is blank.
I've also tried the following for saving to no avail.
my_fig = plt.cgf()
my_fig.savefig(...filepath...)
Basically, it seems that creating a figure and axes, and calling ax.imshow() is not adding the image to my axes, nor are the ax.add_patch() calls doing anything to the axes.
I've also tried it without creating separate axes, as with:
plt.figure()
plt.imshow(image)
my_axes = plt.gca()
my_axes.add_patch(plt.Rectangle(...params...)
plt.savefig(...filepath...)
Again, the resulting figure is blank and has 0 axes.
I know I'm probably missing an obvious step, but I can't figure out what it is, and even copying and pasting code has been no help.
Edit: Adding complete code in response to comment
import cv2
from matplotlib import pyplot as plt
img = './1.png' # 364x364
image = cv2.imread(img)
fig, ax = plt.subplots()
ax.imshow(image)
color = (1, 0, 0, 1)
ax.add_patch(plt.Rectangle((139, 25), 85, 336,
color = color,
fill = False,
linewidth = 2))
plt.savefig('./annotated.png')
I also faced the same problem and here is what worked for me.
from matplotlib.patches import Rectangle
fig,ax = plt.subplots(figsize=(15,12))
ax.imshow(frames[0])
x,y,w,h = bboxes[0]
ax.add_patch(Rectangle((x,y),w,h, linewidth=3, edgecolor='r', facecolor='none'))
plt.axis('off')
plt.savefig("out.png",bbox_inches='tight',pad_inches=0)
plt.show()
I was also getting a blank image on disk when plt.show() was written before plt.savefig()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With