
from pypylon import pylon
import cv2 as cv
import numpy as np
camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
camera.Open()
nodemap = camera.GetNodeMap()
width = nodemap.GetNode("Width")
height = nodemap.GetNode("Height")
print("width = %d"%width.GetValue())
print("height = %d"%height.GetValue())
w = 1280
h = 1024
width.SetValue(w)
height.SetValue(h)
offsetX = nodemap.GetNode("OffsetX")
offsetY = nodemap.GetNode("OffsetY")
offsetX.SetValue(0*16)
offsetY.SetValue(0*16)
autoexp = False
exptime = 9500 # en microsecondes 
exposureAuto = nodemap.GetNode("ExposureAuto")
if autoexp:
	exposureAuto.FromString("Once") # réglage automatique de l'exposition : une seule fois
else:
	exposureAuto.FromString("Off")
	exposureTime = nodemap.GetNode("ExposureTime")
	exposureTime.FromString("%d"%exptime)
balanceWhiteAuto = nodemap.GetNode("BalanceWhiteAuto")
balanceWhiteAuto.FromString("Once")
framerate = 100 # en Hz
nodemap.GetNode("AcquisitionFrameRateEnable").FromString("1")
nodemap.GetNode("AcquisitionFrameRate").FromString("%d"%framerate)
framerate = nodemap.GetNode("ResultingFrameRate").GetValue()
print("Framerate = %f"%framerate)
converter = pylon.ImageFormatConverter()
converter.OutputPixelFormat = pylon.PixelType_BGR8packed
converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned	
camera.MaxNumBuffer = 1000 # taille de la file (nombre de tampons maximal)
camera.StartGrabbing(pylon.GrabStrategy_OneByOne)
fourcc = cv.VideoWriter_fourcc(*'mpg1')
videoWriter = cv.VideoWriter('video.mpg',fourcc,30,(w,h))
f = 0
numFrames = 1000
while camera.IsGrabbing() and f < numFrames:
	timeout = 10000 # ms, temps d'attente maximal de l'image
	grabResult = camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException)
	if grabResult.GrabSucceeded():
		skip = grabResult.GetNumberOfSkippedImages()
		if skip!=0: print("skip : %d"%skip)
		image = converter.Convert(grabResult)
		img = image.GetArray() # image au format OpenCV (BGR), tableau np.ndarray
		# placer ici le traitement d'image 
		videoWriter.write(img)
		f += 1
	grabResult.Release()
print("%d frames"%f)
camera.StopGrabbing()
camera.Close()
cv.destroyAllWindows()
videoWriter.release()	
				