#!/usr/bin/python
# Tune MSER algorithm coefficients

import sys

import cv
import cv2

from pllm.vision.algo import mser_segments
from pllm.vision.util import draw_segments

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: mser_tune IMG_FILE")
        sys.exit(1)


    cv.NamedWindow("preview", cv.CV_WINDOW_AUTOSIZE)
    cv.NamedWindow("controls", cv.CV_WINDOW_AUTOSIZE)
    cv.CreateTrackbar("delta", "controls", 3, 255, lambda x: x)
    cv.CreateTrackbar("minArea", "controls", 1500, 10000, lambda x: x)
    cv.CreateTrackbar("maxArea", "controls", 34400, 100000, lambda x: x)
    cv.CreateTrackbar("maxVariation", "controls", 10, 100, lambda x: x)
    cv.CreateTrackbar("minDiversity", "controls", 50, 100, lambda x: x)

    im = cv2.imread(sys.argv[1])

    while True:
        gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

        delta = cv.GetTrackbarPos("delta", "controls")
        min_area = cv.GetTrackbarPos("minArea", "controls")
        max_area = cv.GetTrackbarPos("maxArea", "controls")
        max_variation = cv.GetTrackbarPos("maxVariation", "controls") / 100.
        min_diversity = cv.GetTrackbarPos("minDiversity", "controls") / 100.

        segs = mser_segments(im, delta, min_area, max_area,
                             max_variation, min_diversity)

        res = im.copy()
        res = draw_segments(res, segs)

        cv2.imshow('preview', res)

        if 0xFF & cv2.waitKey(5) == 27:
            break

    cv2.destroyAllWindows()
