# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (1920, 1088)
camera.framerate = 5.0
rawCapture = PiRGBArray(camera, size=(1920, 1088))

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 5, (1920, 1088))

# allow the camera to warmup
time.sleep(0.1)

#counter
nr = 0

# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    # grab the raw NumPy array representing the image, then initialize the timestamp
    # and occupied/unoccupied text
    image = frame.array

    #make a writable copy
    ndvi = image.copy()

    #calcualte NDVI index
    ndvi[:, :, 0] = (ndvi[:, :, 0] - ndvi[:, :, 0]) / (ndvi[:, :, 0] + ndvi[:, :, 0] + 0.00000001)

    # write the frame
    cv2.imwrite("ndvi" + str(nr) + ".png", ndvi)

    key = cv2.waitKey(1) & 0xFF
    rawCapture.truncate(0)

    #increase counter
    nr+=1

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break
