siamese/coco_cvat_gen.py

87 lines
2.1 KiB
Python
Raw Permalink Normal View History

2021-08-16 16:32:21 +02:00
import json, os
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
no_label = 0
small = 0
passed = 0
count = 0
2021-09-20 08:06:52 +02:00
def findAnnotationName(annotationId, annotations):
for c in annotations['categories']:
2021-08-16 16:32:21 +02:00
if c['id'] == annotationId:
return c['name']
2021-09-20 08:06:52 +02:00
def findAnnotationToId(ident, annotations):
for annotation in annotations['annotations']:
2021-08-16 16:32:21 +02:00
img_an = annotation['image_id']
if img_an == ident:
return annotation
def show(pil, pause=0.2):
ImageNumpyFormat = np.asarray(pil)
plt.imshow(ImageNumpyFormat)
plt.draw()
plt.pause(pause) # pause how many seconds
plt.close()
2021-09-20 08:06:52 +02:00
def parseImage(coImg, annotations, subset):
global no_label, small, passed
2021-08-16 16:32:21 +02:00
# open image file
2021-09-20 08:06:52 +02:00
path = "coco/"+subset+"/images/" + coImg['file_name'].split('/')[4]
2021-08-16 16:32:21 +02:00
img = Image.open(path)
2021-09-20 08:06:52 +02:00
an = findAnnotationToId(coImg['id'], annotations)
2021-08-16 16:32:21 +02:00
if an == None:
no_label += 1
return
c = an['bbox']
crop = img.crop((c[0], c[1], c[0]+c[2], c[1]+c[3]))
if crop.width < 64 or crop.height < 64:
small += 1
return
2021-09-20 08:06:52 +02:00
imagePath = f"classified/classified_{subset}/{findAnnotationName(an['category_id'], annotations)}/{an['id']}.png"
2021-08-16 16:32:21 +02:00
os.makedirs(os.path.dirname(imagePath), exist_ok=True)
crop.save(imagePath)
passed += 1
2021-09-20 08:06:52 +02:00
def parseSubset(subset):
global count
print("loading" + subset + "annotations...")
annotations = json.load(open('./coco/'+subset+'/annotations/instances_default.json'))
print("done")
2021-08-16 16:32:21 +02:00
2021-09-20 08:06:52 +02:00
for coImg in annotations['images']:
parseImage(coImg, annotations,subset)
2021-08-16 16:32:21 +02:00
count += 1
if count % 100 == 0:
print("status:")
print(f"no labels: {no_label}")
print(f"to small: {small}")
print(f"passed: {passed}")
print("-----")
2021-09-20 08:06:52 +02:00
if __name__ == "__main__":
parseSubset('donaulager')
parseSubset('instantina')
parseSubset('lkw_walter_2019')
parseSubset('lkw_walter_2020')
parseSubset('tkl')
parseSubset('vw_bratislava')
parseSubset('vw_portugal')
parseSubset('watt')
parseSubset('wls')