How to save an image from a custom COCO dataset with its annotations overlaid on top of it

1.7k Views Asked by At

I created a custom COCO dataset. Now suppose I have valid image metadata in image_data. I can display the image and the annotation with

import skimage.io as io
import matplotlib.pyplot as plt

image_directory ='my_images/'

image = io.imread(image_directory + image_data['file_name'])
plt.imshow(image); plt.axis('off')
pylab.rcParams['figure.figsize'] = (8.0, 10.0)
annotation_ids = example_coco.getAnnIds(imgIds=image_data['id'], catIds=category_ids, iscrowd=None)
annotations = example_coco.loadAnns(annotation_ids)
example_coco.showAnns(annotations)

At this point, I'll be able to see annotations overlaid over the image. However, I want to save the image with the annotations overlaid on top of it. How can I do that? I tried

io.imsave(fname="test.png", arr=image)

But it doesn't work. It just saves the original image, without any annotation.

1

There are 1 best solutions below

0
On

You can save figure/plot using

 plt.savefig("test.png", bbox_inches='tight', pad_inches=0)

There are some parameters to remove margins.


Working example

import skimage.io as io
import matplotlib.pyplot as plt

image = io.imread("https://homepages.cae.wisc.edu/~ece533/images/lena.png")

plt.imshow(image)
plt.axis('off')
plt.annotate("Lena", (10, 20))
plt.savefig("test.png", bbox_inches='tight', pad_inches=0) # if you want to display then `savefig()` has to be before `show()` 
#plt.show()

enter image description here


Eventually you can use PIL/pillow to draw directly on image

import skimage.io as io
from PIL import Image, ImageDraw, ImageFont

image = io.imread("https://homepages.cae.wisc.edu/~ece533/images/lena.png")

img = Image.fromarray(image)
draw = ImageDraw.Draw(img)
draw.text((10,10), "Lena", font=ImageFont.truetype("arial", 20), fill=(0,0,0))
img.save('test.png')