
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 = 10000 # 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 = 30 # 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			   
				   
cv.namedWindow('basler', cv.WINDOW_NORMAL)
				   
camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)	   
				   
while camera.IsGrabbing():
	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 
		cv.imshow('basler', img)
		k = cv.waitKey(1)
		if k == ord('q'):
			break
	grabResult.Release()
    
camera.StopGrabbing()
camera.Close()
cv.destroyAllWindows()				
					