import numpy as np
import pandas as pd

import os
"""
#### Train csv contains all individual masks. Goal of notebook is to combine all annotations into a single np array for training
"""
df = pd.read_csv('../input/sartorius-cell-instance-segmentation/train.csv')
df.describe()
"""
#### All images are 520x704
"""
height = 520
width = 704
"""
# Make all Masks
"""
#Go through all images
for file_id in df['id'].unique():
    file_name = f'{file_id}_mask.npy'
    test_mask = np.zeros((height*width))
    
    masks = df[df['id']==file_id]['annotation']
    
    #Making all masks value 1 in np array
    for mask in masks:
        pixel = []
        length = []
        for i, val in enumerate(mask.split()):
            if i % 2 == 0:
                pixel.append(int(val)-1)
            else:
                length.append(int(val))
        for pixel, length in zip(pixel,length):
            test_mask[pixel-1:pixel+length] = 1
    
    test_mask = test_mask.reshape((height,width))
    
    np.save(file_name,test_mask)
"""
# Check Random Image and Mask
"""
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import random

root = '../input/sartorius-cell-instance-segmentation/train/'
images = os.listdir(root)
images = [x.split('.')[0] for x in images]
index=random.randint(0, len(images))

file_id = images[index]

image = root+file_id+'.png'
mask = np.load(file_id+'_mask.npy')

plt.figure(figsize = (15,10))
plt.title(file_id)
img = mpimg.imread(image)
imgplot = plt.imshow(img, cmap='gray')
plt.show()

plt.figure(figsize = (15,10))
plt.imshow(mask, cmap='gray')
plt.show()