# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import mmcv
import matplotlib.pyplot as plt
import math 
from matplotlib.patches import Rectangle, Polygon
from PIL import Image
import numpy as np
import os
import shutil
import json
import cv2
from tqdm import tqdm


def npxywha2vertex(box):
    """
    use radian
    X=x*cos(a)-y*sin(a)
    Y=x*sin(a)+y*cos(a)
    """
    batch = box.shape[0]

    center = box[:,:2]
    w = box[:,2]
    h = box[:,3]
    rad = box[:,4]

    # calculate two vector
    verti = np.empty((batch,2), dtype=np.float32)
    verti[:,0] = (h/2) * np.sin(rad)
    verti[:,1] = - (h/2) * np.cos(rad)

    hori = np.empty((batch,2), dtype=np.float32)
    hori[:,0] = (w/2) * np.cos(rad)
    hori[:,1] = (w/2) * np.sin(rad)

    tl = center + verti - hori
    tr = center + verti + hori
    br = center - verti + hori
    bl = center - verti - hori

    return np.concatenate([tl,tr,br,bl], axis=1)


path = "../../../data/Phamacity/"


def json2txtAnnotations(path, outputPath):
    for filename in os.listdir(path):
        # print(filename)
        if filename.endswith(".json"):
            f = open(path + filename)
            data = json.load(f)
            for anno in data['annotations']: 
                # print(anno)
                image_id = anno['image_id']
                bbox = anno['bbox']
                bbox[4] = bbox[4] / 180 * math.pi
                bbox = np.array(bbox)
                bbox = npxywha2vertex(bbox[np.newaxis])
                with open(outputPath + image_id+'.txt', 'w') as txt:
                    for cor in bbox[0]:
                        txt.write(cor.astype('str') + ' ')
                    txt.write('person 0\n')
            f.close()
        


def png2jpg(path, outputPath):
    for dir in os.listdir(path):
        if os.path.isdir(path+dir):
            print(dir)
            for filename in tqdm(os.listdir(path+dir)):
                if filename.endswith(".jpg"):
                    portion = os.path.splitext(filename)
                    img = cv2.imread(path+dir+'/'+filename)
                    cv2.imwrite(outputPath + portion[0] + '.png', img)
                    # shutil.copy2(path+dir+'/'+filename, path+'images')
                


json2txtAnnotations(path, "../../../data/PhamacityDota/anno/")

png2jpg(path, "../../../data/PhamacityDota/images/")



StarcoderdataJupyterScriptsDedupFiltered