Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. # This code is public domain.
  2.  
  3. import json
  4.  
  5. data = {}
  6. images = {}
  7.  
  8.  
  9. def imagename_to_id(name):
  10. return list(filter(lambda img: img['file_name'] == name, data['images']))[0]['id']
  11.  
  12.  
  13. def load(filename='COCO.json'):
  14. """Load the given JSON file."""
  15. global data, images
  16. with open(filename) as input:
  17. data = json.load(input)
  18. images = {img['id']: img for img in data['images']}
  19.  
  20.  
  21. def get_images():
  22. """Return all images."""
  23. return data['images']
  24.  
  25.  
  26. def get_annotations(image=None):
  27. """Return the annotations for the given image or all annotations if no argument or a falsy argument is given."""
  28. if not image:
  29. return data['annotations']
  30. img_id = imagename_to_id(image)
  31. return list(filter(lambda a: a['image_id'] == img_id, data['annotations']))
  32.  
  33.  
  34. def get_with(object_type=None):
  35. """
  36. Return the files that are annotated with the given object class ('balise', 'main_signal' oder 'distant_signal').
  37. If no argument or a falsy argument is given, returns all files that have at least one annotation.
  38. """
  39. if not object_type:
  40. with_annots = set(map(lambda a: a['image_id'], data['annotations']))
  41. return [images[id]['file_name'] for id in with_annots]
  42. cat_id = [cat['id'] for cat in filter(lambda cat: cat['name'] == object_type, data['categories'])][0]
  43. annots = filter(lambda annot: annot['category_id'] == cat_id, data['annotations'])
  44. return list(map(lambda annot: images[annot['image_id']]['file_name'], annots))
  45.  
  46.  
  47. if __name__ == '__main__':
  48. """Load the input file, invoke get_with() and print the result."""
  49. load('COCO.json')
  50. print(get_with())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement