#! /usr/bin/python
from __future__ import division, print_function
import numpy as np
import os
import cv2
import subprocess
import matplotlib.pyplot as plt
import glob


image_in_dir = '/home/user/adapt_ws/data/images0'
image_out_dir = '/home/user/adapt_ws/data/images00'
line_read_first = 3648

# Negative indicates reading from bottom to top.
line_read_speed = -72960    # lines/s

num_segments = 5

img_fnames = glob.glob('%s/*.jpg' % image_in_dir)
img_fnames = sorted(img_fnames)

try:
    os.makedirs(image_out_dir)
except (OSError, IOError):
    pass

for i, img_fname in enumerate(img_fnames):
    t = float(os.path.splitext(os.path.split(img_fname)[1])[0])/1000000
    img = cv2.imread(img_fname)
    row_range = np.linspace(0, img.shape[0], num_segments + 1)
    row_range = np.round(row_range).astype(np.int)
    for k in range(num_segments):
        center_row = (row_range[k] + row_range[k+1])/2
        tk = t + (line_read_first - center_row)/line_read_speed
        fname_out = '%s/%i.png' % (image_out_dir, int(np.round(tk*1000000)))
        img_out = np.zeros_like(img)
        img_out[row_range[k]:row_range[k+1], :, :] = img[row_range[k]:row_range[k+1], :, :]
        cv2.imwrite(fname_out, img_out)



if False:
    # Path to Colmap images.bin that has been geo-registered.
    images_bin_fname = '%s/images.bin' % (colmap_sparse_dir)

    # Camera model cameras.bin path.
    camera_bin_fname = '%s/cameras.bin' % (colmap_sparse_dir)

    # Points cameras.bin path.
    points_bin_fname = '%s/points3D.bin' % (colmap_sparse_dir)