def CaptureVideo(self, filename='Capture', format='MJPG', runtime=10.0): print(" in Capture Video!! ", runtime, filename) # print(" Current folder ", os.getcwd()) framerate = 15.0 numImages = max(15, 1 + runtime * framerate) self.Stop() time.sleep(0.02) t0 = time.time() avi = PyCapture2.AVIRecorder() self.camera.StartCapture() for i in range(numImages): try: image = self.camera.cam.retrieveBuffer() except PyCapture2.Fc2error as fc2Err: print("dropped frame:", fc2Err) continue if i == 0: if format == "AVI": avi.AVIOpen(filename, framerate) elif format == "MJPG": print(" Open MJPG video") avi.MJPGOpen(filename, framerate, 75) elif format == "H264": avi.H264Open(filename, framerate, image.getCols(), image.getRows(), 1000000) else: print("Specified format is not available.") return # print(i, image) avi.append(image) print("saved file %s time = %.1f " % (filename, time.time() - t0)) avi.close() self.Stop() self.Start()
def saveAviHelper(cam, fileFormat, fileName, frameRate): i = 0 avi = PyCapture2.AVIRecorder() #for i in range(numImages): while (1): try: try: ret, image = capIm(cam) if not ret: print("no image") break except PyCapture2.Fc2error as fc2Err: print "Error retrieving buffer : ", fc2Err continue print "Grabbed image {}".format(i) if (i == 0): if fileFormat == "AVI": avi.AVIOpen(fileName, frameRate) elif fileFormat == "MJPG": avi.MJPGOpen(fileName, frameRate, 75) elif fileFormat == "H264": avi.H264Open(fileName, frameRate, image.getCols(), image.getRows(), 1000000) else: print "Specified format is not available." return avi.append(image) print "Appended image {}...".format(i) i = 1 + i #print i except KeyboardInterrupt: break print "Appended {} images to {} file: {}...".format( i, fileFormat, fileName) avi.close()
def main(camera_serial_number, fileName_prefix): # Print PyCapture2 Library Information printBuildInfo() # Ensure sufficient cameras are found bus = PyCapture2.BusManager() numCams = bus.getNumOfCameras() print "Number of cameras detected: ", numCams if not numCams: print "Insufficient number of cameras. Exiting..." exit() c = PyCapture2.Camera() # c.connect(bus.getCameraFromIndex(camera_index)) c.connect(bus.getCameraFromSerialNumber(camera_serial_number)) # !!! # Power on the Camera cameraPower = 0x610 powerVal = 0x80000000 c.writeRegister(cameraPower, powerVal) # Waiting for camera to power up retries = 10 timeToSleep = 0.1 #seconds for i in range(retries): sleep(timeToSleep) try: regVal = c.readRegister(cameraPower) except PyCapture2.Fc2error: # Camera might not respond to register reads during powerup. pass awake = True if regVal == powerVal: break awake = False if not awake: print "Could not wake Camera. Exiting..." exit() # Configure trigger mode triggerMode = c.getTriggerMode() triggerMode.onOff = True triggerMode.mode = 14 triggerMode.parameter = 0 triggerMode.polarity = 1 triggerMode.source = 0 # Using external trigger !!! c.setTriggerMode(triggerMode) # Set external trigger #externalTrigger = 0x830 #fireVal = 0x83100000 #c.writeRegister(externalTrigger, fireVal) c.setConfiguration(grabTimeout=100000) # Print camera details fmt7info, supported = c.getFormat7Info(1) # Check whether pixel format mono8 is supported if PyCapture2.PIXEL_FORMAT.RAW8 & fmt7info.pixelFormatBitField == 0: print "Pixel format is not supported\n" exit() # Configure camera format7 settings # Left, Top, Width, Height # fmt7imgSet = PyCapture2.Format7ImageSettings(1, 0, 0, fmt7info.maxWidth, fmt7info.maxHeight, PyCapture2.PIXEL_FORMAT.RAW8) # fmt7imgSet = PyCapture2.Format7ImageSettings(0, 368, 296, 496, 416, PyCapture2.PIXEL_FORMAT.RAW8) # Camera 1 side # fmt7imgSet = PyCapture2.Format7ImageSettings(1, 144, 162, 304, 350, PyCapture2.PIXEL_FORMAT.RAW8) # Camera 1 # Automatically get settings from the GUI (Han 20210414) setting_in_gui = c.getFormat7Configuration()[0] fmt7imgSet = PyCapture2.Format7ImageSettings(setting_in_gui.mode, setting_in_gui.offsetX, setting_in_gui.offsetY, setting_in_gui.width, setting_in_gui.height, setting_in_gui.pixelFormat) fmt7pktInf, isValid = c.validateFormat7Settings(fmt7imgSet) if not isValid: print "Format7 settings are not valid!" exit() c.setFormat7ConfigurationPacket(fmt7pktInf.maxBytesPerPacket, fmt7imgSet) # Enable camera embedded timestamp c.setEmbeddedImageInfo(timestamp=True) # Configure camera buffer settings #bufferFrame = PyCapture2.Config() #bufferFrame.numBuffers = 64 #bufferFrame.grabMode = 1 #bufferFrame.highPerformanceRetrieveBuffer = True c.setConfiguration(numBuffers=64) c.setConfiguration(grabMode=1) c.setConfiguration(highPerformanceRetrieveBuffer=True) # import pdb; pdb.set_trace() # Print camera details printCameraInfo(c) print "\n---------------- \n" print "Camera: ", fileName_prefix # -------------------------------------------------- # Start acquisition c.startCapture() avi = PyCapture2.AVIRecorder() #fRateProp = c.getProperty(PyCapture2.PROPERTY_TYPE.FRAME_RATE) #frameRate = fRateProp.absValue frameRate = 30 trialIdx = 1 fileName = fileName_prefix + "{}.avi".format(trialIdx) #image = c.retrieveBuffer() #avi.AVIOpen(fileName, frameRate) avi.MJPGOpen(fileName, frameRate, 95) # Grab images try: while True: # Loop per trial frame_count = 0 intervals = [] last_frame = 0 print "Trial=", '{:<4d}'.format(trialIdx), " ", while True: try: image = c.retrieveBuffer() avi.append(image) frame_count += 1 this_frame = time() intervals.append(this_frame - last_frame) # print image.getDataSize(), (this_frame - last_frame)*1000 last_frame = this_frame if frame_count > 0: # Once first frame received, set Timeout to 100ms c.setConfiguration(grabTimeout=trial_time_out) except PyCapture2.Fc2error as fc2Err: #print "Error retrieving buffer : ", fc2Err avi.close() # Close file trialIdx += 1 fileName = fileName_prefix + "{}.avi".format(trialIdx) #avi.AVIOpen(fileName, frameRate) avi.MJPGOpen(fileName, frameRate, 95) #avi.H264Open(fileName, frameRate, image.getCols(), image.getRows(), 100000) c.setConfiguration(grabTimeout=100000) intervals.append( time() - last_frame ) # Gap between receiving the last frame and starting new file (including 100ms Timeout) #continue break #print "max frame interval = ", intervals #print np.histogram(intervals) interval_count, interval_edges = np.histogram(intervals[1:-1], 7) interval_bins = (interval_edges[:-1] + interval_edges[1:]) / 2 print '{:5d} @ {:.3f} Hz'.format(frame_count, 1 / np.mean(intervals[1:-1])), print ''.join([ " | {:.2f}ms:{:<4d}".format(bb * 1000, nn) for nn, bb in zip(interval_count, interval_bins) if nn > 0 ]), print '>> gap={:.3f}ms'.format(intervals[-1] * 1000) except KeyboardInterrupt: # Ctrl-C pass c.setTriggerMode(onOff=False) print "Finished grabbing images!" c.stopCapture() c.disconnect()
def captureVideo(idxCam, config, startEvent, abortEvent): nVideos = 0 nFrames = 0 videoType = config["DEFAULT"]["videoType"] videoDuration = config["DEFAULT"].getfloat("videoDuration") frameRate = config["DEFAULT"].getfloat("frameRate") nPulseFrames = int(config["DEFAULT"].getfloat("analogOutDuration") * frameRate) nPeriodFrames = int(config["DEFAULT"].getfloat("analogOutPeriod") * frameRate) nSessionFrames = int(config["DEFAULT"].getfloat("sessionDuration") * frameRate) nVideoFrames = int(videoDuration * frameRate) # initialize our random frame offset maxPeriodOffset = config["DEFAULT"].getfloat("analogOutPeriodRange") nOffsetFrames = nPeriodFrames + getRandomFrameOffset( maxPeriodOffset, frameRate) recordIndefinitely = nSessionFrames == 0 ext = getVideoExtension(videoType) cameraName = "cam{:01}".format(idxCam) cameraPath = os.path.join(config["DEFAULT"]["dataPath"], config["DEFAULT"]["sessionName"], cameraName) processName = mp.current_process().name vid = PyCapture2.AVIRecorder() # get the analog input mapping for frame code output pinMap, maxValue = getAnalogPinMap(config["DEFAULT"]["analogPinMap"]) address = int(config["DEFAULT"]["analogOutAddress"], base=16) # get and connect the camera bus = PyCapture2.BusManager() camera = PyCapture2.Camera() camera.connect(bus.getCameraFromIndex(idxCam)) # wait for the go signal startEvent.wait(0.5) camera.startCapture() time.sleep(0.1) capturingVideo = True while capturingVideo: # open up new video and log files videoFileName = "{}_{:06}".format(cameraName, nVideos) videoFilePath = os.path.join(cameraPath, "{}.{}".format(videoFileName, ext)) logFilePath = os.path.join(cameraPath, "{}.txt".format(videoFileName)) if videoType == "H264": vid.H264Open(filename=videoFilePath.encode("utf8"), width=640, height=480, framerate=frameRate, bitrate=config["DEFAULT"].getint("bitrateH264")) elif videoType == "MJPG": vid.MJPGOpen(filename=videoFilePath.encode("utf8"), framerate=frameRate, quality=config["DEFAULT"].getint("qualityMJPG")) elif videoType == "AVI": vid.AVIOpen(filename=videoFilePath.encode("utf8"), framerate=frameRate) with open(logFilePath, 'w') as log: # the frame of the first trigger lastTriggerFrame = 0 analogValue = 1 # acquire and append camera images indefinitely until # the user cancels the operation for ii in range(nVideoFrames): # end session if recording duration exceeds user specified # duration or if user aborts if recordIndefinitely and abortEvent.is_set(): capturingVideo = False break elif not recordIndefinitely and nFrames >= nSessionFrames: capturingVideo = False abortEvent.set() break try: # acquire camera image and stamp logfile image = camera.retrieveBuffer() vid.append(image) log.write("{}\t{}\n".format(ii + 1, getTimestamp(datetime.now()))) nFrames += 1 except PyCapture2.Fc2error as error: print( "{}: error retrieving buffer ({}): dropping frame {}.". format(processName, error, ii)) continue except: pass try: if idxCam == 0: # output an analog value to synchronize (and code info) # set special analog value for start of files if ii == 0: setAnalogOutputValue(maxValue, pinMap, address) elif ii in (2 * nPulseFrames, 4 * nPulseFrames): setAnalogOutputValue(0, pinMap, address) elif ii == 3 * nPulseFrames: setAnalogOutputValue(nVideos % (maxValue + 1), pinMap, address) elif ii > 4 * nPulseFrames and ( ii - lastTriggerFrame) == nOffsetFrames: setAnalogOutputValue(analogValue, pinMap, address) analogValue = analogValue + 1 if analogValue < maxValue else 1 lastTriggerFrame = ii elif ii > 4 * nPulseFrames and ( ii - lastTriggerFrame) == nPulseFrames: setAnalogOutputLow(address) # set a new random trigger shift nOffsetFrames = nPeriodFrames + getRandomFrameOffset( maxPeriodOffset, frameRate) except: pass # save and write the last video file # note that this will silently fail if file size >2 GB! vid.close() try: print("\t\t{}: wrote {}.{} @ {}.".format( processName, videoFileName, ext, getTimestamp(datetime.now()))) except: pass # increment the video counter (unless interrupted) if capturingVideo: nVideos += 1