import cv2
import numpy as np
import struct
import time
import sys

log_file = sys.argv[1] if len(sys.argv) > 1 else 'lepton_log.bin'
output_folder = 'videos'

fourcc = cv2.VideoWriter_fourcc(*'XVID')
leptonVideoWriter = cv2.VideoWriter(output_folder+'/lepton.avi', fourcc, 10.0, (160, 120), False)
gridEyeVideoWriter = cv2.VideoWriter(output_folder+'/gridEye.avi', fourcc, 10.0, (320, 320), False)
#cv2.resizeWindow('image', 320, 320)
with open(log_file, 'rb') as f:
    while 1:
        leptonData = f.read(38400)
        if len(leptonData) != 38400:
            break
        leptonImg = np.array(struct.unpack("<19200H", leptonData), dtype=np.uint16).reshape((120, 160))
        b = leptonImg.copy()
        for x in range(160):
            for y in range(120):
                b[y][x] = ((leptonImg[y][x]&0xff)<<8) + (leptonImg[y][x]>>8)
        b = cv2.normalize(b, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
        b = b.astype(np.uint8)
        cv2.imshow("image", cv2.resize(b, (427, 320)))
        leptonVideoWriter.write(b)
        
        gridEyeData = f.read(4*64)
        gridEyeImg = np.frombuffer(gridEyeData, dtype=np.uint8).reshape((32, 8))
        reshapeImg = np.zeros((16,16), dtype=np.uint8)
        reshapeImg[0:8, 0:8] = gridEyeImg[0:8]
        reshapeImg[0:8, 8:16] = gridEyeImg[8:16]
        reshapeImg[8:16, 0:8] = gridEyeImg[16:24]
        reshapeImg[8:16, 8:16] = gridEyeImg[24:32]
        reshapeImg = cv2.normalize(reshapeImg, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
        cv2.imshow("gridEyeImg", cv2.resize(reshapeImg, (320, 320)))
        gridEyeVideoWriter.write(cv2.resize(reshapeImg, (320, 320)))
        key = cv2.waitKey(10)
        if key == ord('q'):
            break

leptonVideoWriter.release()
gridEyeVideoWriter.release()
cv2.waitKey(0)
cv2.destroyAllWindows()