#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import os.path
import os.path.join
import cv2
import sys


"""Module for converting alpha channel masks to binary masks 
   Usage:
   > python BinarizeMasks.py <inputDirectoryPath> <outputDirectoryPath>
   
   Input arguments:
   * inputDirectoryPath - a path to a directory containing input alpha channel 
    masks
   * outputDirectoryPath - output path for the target masks
   
"""

__author__ = "Ondrej Klima"
__copyright__ = "Copyright 2020"
__credits__ = ["Ondrej Klima"]
__email__ = "iklima@fit.vutbr.cz"
__license__ = "BUT"
__version__ = "1.0"
__maintainer__ = "Ondrej Klima"

def main():
    # Parsing input arguments 
    argv = sys.argv
    
    try:
        inputPath = argv[1]
    except IndexError:
        raise IndexError('Input directory path must be supplied as an argument')

    try:
        outputPath = argv[2]
    except IndexError:
        raise IndexError('Output directory path must be supplied as an argument')

    N = len([name for name in os.listdir(inputPath) if os.path.isfile(os.path.join(inputPath, name))])
    
    for i in range(N):
        image = cv2.imread(os.path.join(inputPath, '%d.png' % i), cv2.IMREAD_UNCHANGED)
        channels = cv2.split(image)
        ret, thresh = cv2.threshold(channels[3], 1, 255, cv2.THRESH_BINARY)
        cv2.imwrite(os.path.join(outputPath, '%d.png') % i, thresh)

if __name__ == "__main__":
    main()