from scipy.io import loadmat
import numpy as np
import json

mat = loadmat('mpii_human_pose_v1_u12_1.mat')

count = len(mat['RELEASE']['annolist'][0, 0][0])
samples = []
for idx, anno in enumerate(mat['RELEASE']['annolist'][0, 0][0]):
    try:
        filename = anno['image']['name'][0, 0][0]
        annopoints = anno['annorect']['annopoints'][0]

        # each annotated human in image appended in here:
        labels = []

        for aidx in range(0, len(annopoints)):
            try:
                annopoint = annopoints[aidx]

                # head rectangle:
                x1 = anno['annorect']['x1'][0][aidx][0][0]
                y1 = anno['annorect']['y1'][0][aidx][0][0]
                x2 = anno['annorect']['x2'][0][aidx][0][0]
                y2 = anno['annorect']['y2'][0][aidx][0][0]

                # scale:
                scale = anno['annorect']['scale'][0][aidx][0][0]

                # rough human center position on image:
                pos_x = anno['annorect']['objpos'][0][aidx][0][0][0][0][0]
                pos_y = anno['annorect']['objpos'][0][aidx][0][0][1][0][0]

                # human joints/landmarks:
                landmarks = []
                points = annopoint['point'][0][0]
                for lidx in range(0, len(points['id'][0])):
                    joint = points['id'][0][lidx][0][0]
                    x = float(points['x'][0][lidx][0][0])
                    y = float(points['y'][0][lidx][0][0])
                    visible = float(points['y'][0][lidx][0][0])
                    landmarks.append({
                        'joint': joint,
                        'x': x,
                        'y': y,
                        'visible': visible
                    })

                labels.append({
                    'head': (x1, y1, x2, y2),
                    'scale': scale,
                    'pos': (pos_x, pos_y),
                    'landmarks': landmarks
                })
            except Exception as e:
                print(e)

        if len(landmarks) > 0:
            samples.append({
                'filename': filename,
                'idx': idx,
                'landmarks': landmarks,
                'count': count
            })
    except Exception as e:
        print(e)
        print(anno.dtype)
        print(anno['annorect'])

print(len(samples), count)