예제 #1
0
    def capture(self):
        bus = PyCapture2.BusManager()
        cam = PyCapture2.Camera()
        maxWidth = 2448
        maxHeight = 2048

        cam.connect(bus.getCameraFromIndex(0))
        #cam.setProperty(type = PyCapture2.PROPERTY_TYPE.AUTO_EXPOSURE, absValue = self.exp_time)
        cam.setProperty(type=PyCapture2.PROPERTY_TYPE.GAIN, absValue=self.gain)
        fmt7imgSet = PyCapture2.Format7ImageSettings(
            0, 0, 0, maxWidth, maxHeight, PyCapture2.PIXEL_FORMAT.MONO8)
        fmt7pktInf, isValid = cam.validateFormat7Settings(fmt7imgSet)

        if not isValid:
            print("Format7 settings are not valid!")
            exit()

        cam.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket,
                                          fmt7imgSet)

        cam.startCapture()

        for i in range(self.n_images):
            self.grabImages(cam)

            for filename in os.listdir("."):
                print(filename)
                if filename.startswith("fc2"):
                    os.rename(filename,
                              "{}.{}.tif".format(self.input_angle, i))

        cam.stopCapture()
예제 #2
0
def init(camIndex=0):
    """
        This function initialises the connection with camera with an index specified by the camIndex parameter and starts the capture process
        WARNING: After init() is called, the camera must be properly closed using .close() method
    """
    global camInitialised
    print("Initialising connection to camera ", camIndex)
    cam.connect(bus.getCameraFromIndex(camIndex))
    __printCameraInfo__(cam)
    # set the format to RAW16 using format 7
    fmt7info, supported = cam.getFormat7Info(0)
    global _PIXEL_FORMAT
    # Check whether pixel format _PIXEL_FORMAT is supported
    if _PIXEL_FORMAT & fmt7info.pixelFormatBitField == 0:
        raise RuntimeError("Pixel format is not supported\n")
    fmt7imgSet = PyCapture2.Format7ImageSettings(0, 0, 0, fmt7info.maxWidth,
                                                 fmt7info.maxHeight,
                                                 _PIXEL_FORMAT)
    fmt7pktInf, isValid = cam.validateFormat7Settings(fmt7imgSet)
    if not isValid:
        raise RuntimeError("Format7 settings are not valid!")
    cam.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket,
                                      fmt7imgSet)
    cam.setConfiguration(grabMode=PyCapture2.GRAB_MODE.DROP_FRAMES)

    cam.startCapture()
    camInitialised = True
예제 #3
0
def configure_camera(camera):
    """
    Configure the camera with our expected input
    :param camera:
    :return:
    """
    width, height = constants.IMAGE_WIDTH, constants.IMAGE_HEIGHT
    fmt7info, supported = camera.getFormat7Info(0)
    offset_x = int((fmt7info.maxWidth - width) / 2)
    offset_y = int((fmt7info.maxHeight - height) / 2)
    pxfmt = PyCapture2.PIXEL_FORMAT.RAW8
    fmt7imgSet = PyCapture2.Format7ImageSettings(0, offset_x, offset_y, width,
                                                 height, pxfmt)
    fmt7pktInf, isValid = camera.validateFormat7Settings(fmt7imgSet)
    camera.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket,
                                         fmt7imgSet)

    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.AUTO_EXPOSURE,
                       autoManualMode=True)
    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.SHARPNESS,
                       autoManualMode=True)
    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.SHUTTER,
                       autoManualMode=True)
    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.GAIN, autoManualMode=True)
    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.FRAME_RATE,
                       autoManualMode=True)
    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.AUTO_EXPOSURE, onOff=True)
    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.FRAME_RATE,
                       onOff=True,
                       autoManualMode=False,
                       absValue=40)
    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.GAMMA, onOff=True)
    camera.setProperty(type=PyCapture2.PROPERTY_TYPE.SHARPNESS, onOff=True)
예제 #4
0
def connectpyCapture(camera_):

    printBuildInfo()

    bus = py2.BusManager()

    numCams = bus.getNumOfCameras()

    print "Number of cameras detected: ", numCams

    if not numCams:

        print "Insufficient number of cameras. Exiting..."

        exit()

    c = py2.Camera()
    py2.Config.highPerformanceRetrieveBuffer = True

    c.connect(bus.getCameraFromIndex(camera_))

    printCameraInfo(c)

    #    fmt7info, supported = c.getFormat7Info(0)

    #    print "Connecting to  camera: " , bool

    c.getFormat7Configuration()

    if camera_ == 0:

        fmt7imgSet = py2.Format7ImageSettings(0, 0, 0, 2048, 900,
                                              py2.PIXEL_FORMAT.MONO8)

    else:

        fmt7imgSet = py2.Format7ImageSettings(0, 700, 400, 1040, 1000,
                                              py2.PIXEL_FORMAT.MONO8)

    fmt7pktInf, isValid = c.validateFormat7Settings(fmt7imgSet)

    c.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket,
                                    fmt7imgSet)

    c.startCapture()

    return c
예제 #5
0
파일: camera.py 프로젝트: walachey/wdd2
    def __init__(self,
                 height,
                 width,
                 fps,
                 device,
                 background=None,
                 alpha=None,
                 fullframe_path=None,
                 gain=100):
        super().__init__(height, width, background, alpha)

        self.fps = fps
        self.device = device
        self.fullframe_path = fullframe_path
        self.counter = 0

        bus = PyCapture2.BusManager()
        numCams = bus.getNumOfCameras()

        print(10 * '*' + ' AVAILABLE CAMERAS ' + 10 * '*')
        for i in range(numCams):
            print('\n{})'.format(i + 1))
            self.cap = PyCapture2.Camera()
            self.uid = bus.getCameraFromIndex(i)
            self.cap.connect(self.uid)
            self.print_cam_info(self.cap)
            self.cap.disconnect()

            bus = PyCapture2.BusManager()

        if not numCams:
            raise RuntimeError('No Flea3 camera detected')

        self.cap = PyCapture2.Camera()
        self.uid = bus.getCameraFromSerialNumber(int(device))
        self.cap.connect(self.uid)

        print(10 * '*' + ' SELECTED CAMERA ' + 10 * '*')
        self.print_cam_info(self.cap)

        fmt7imgSet = PyCapture2.Format7ImageSettings(
            PyCapture2.MODE.MODE_4, 0, 0, 2048, 1080,
            PyCapture2.PIXEL_FORMAT.MONO8)
        fmt7pktInf, isValid = self.cap.validateFormat7Settings(fmt7imgSet)
        if not isValid:
            raise RuntimeError("Format7 settings are not valid!")

        self.cap.setFormat7ConfigurationPacket(
            fmt7pktInf.recommendedBytesPerPacket, fmt7imgSet)

        self.cap.setProperty(type=PyCapture2.PROPERTY_TYPE.FRAME_RATE,
                             absValue=fps)
        self.cap.setProperty(type=PyCapture2.PROPERTY_TYPE.AUTO_EXPOSURE,
                             absValue=False)
        self.cap.setProperty(type=PyCapture2.PROPERTY_TYPE.SHUTTER,
                             absValue=1 / fps * 1000)
        self.cap.setProperty(type=PyCapture2.PROPERTY_TYPE.GAIN, absValue=100)

        self.cap.startCapture()
예제 #6
0
    def connect(self):
        """Connect to the camera.

        If currently unattached, automatically connect to any attached
        camera. This method is called for you before any camera operation.
        """
        if not self.camera.isConnected:
            logging.debug('** camera init')
            numCams = self.busManager.getNumOfCameras()

            if numCams == 0:
                self.release()
                raise Error('No cameras detected')

            try:
                uid = self.busManager.getCameraFromIndex(0)
                self.camera.connect(uid)
                self.camera.startCapture()
            except PyCapture2.Fc2error:
                raise Error('Unable to connect to camera')

            # check if PREVIEW is supported
            fmt7info, supported = self.camera.getFormat7Info(
                PyCapture2.MODE.MODE_0)

            fmt7imgSet = PyCapture2.Format7ImageSettings(
                PyCapture2.MODE.MODE_0, 0, 0, fmt7info.maxWidth,
                fmt7info.maxHeight, PyCapture2.PIXEL_FORMAT.RGB)

            fmt7pktInf, isValid = self.camera.validateFormat7Settings(
                fmt7imgSet)

            if not isValid:
                raise Error('Camera does not support Preview mode')

            self.mode_preview = (fmt7pktInf.recommendedBytesPerPacket,
                                 fmt7imgSet)

            logging.debug('** camera connected')
            self.ensure_mode(self.mode_preview)
예제 #7
0
    data = np.array(image.getData())  # np.array() call prevents crash
    shape = (image.getRows(), image.getCols())
    data = data.reshape(shape)

    return data

bus = pc2.BusManager()
numCams = bus.getNumOfCameras()
print("Number of cameras detected:", numCams)

cam = pc2.Camera()
cam.connect(bus.getCameraFromIndex(0))
printCameraInfo(cam)

fmt7info, supported = cam.getFormat7Info(0)
fmt7imgSet = pc2.Format7ImageSettings(0, 0, 0, fmt7info.maxWidth, fmt7info.maxHeight, pc2.PIXEL_FORMAT.MONO8)
fmt7pktInf, isValid = cam.validateFormat7Settings(fmt7imgSet)
cam.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket, fmt7imgSet)

d = pc2.PROPERTY_TYPE.__dict__
props = [key for key in d.keys() if isinstance(d[key], int)]

enableEmbeddedTimeStamp(cam, True)
cam.setProperty(type = pc2.PROPERTY_TYPE.SHUTTER, absControl=True, autoManualMode=False, absValue = 0.5)
cam.setProperty(type = pc2.PROPERTY_TYPE.GAIN, absControl=True, autoManualMode=False, absValue = 12.0)
cam.startCapture()
image = grabImages(cam, 1)
cam.stopCapture()

data = image.getData()
shape = (image.getRows(), image.getCols())
# See the pdf, use PROPERTY, and PROPERTY_TYPE, to set shutter.
# Set video mode to format 7, raw8
# Set height to reduced that is acceptable
# Ensure frame rate if FORMAT7
# go to town.
# test by reseting camera and ensure code resets it, not flycap.

if 0:
    # Check whether pixel format mono8 is supported
    if PyCapture2.PIXEL_FORMAT.MONO8 & fmt7info.pixelFormatBitField == 0:
        print "Pixel format is not supported\n"
        exit()

    # Configure camera format7 settings
    fmt7imgSet = PyCapture2.Format7ImageSettings(0, 0, 0, fmt7info.maxWidth,
                                                 fmt7info.maxHeight,
                                                 PyCapture2.PIXEL_FORMAT.MONO8)
    fmt7pktInf, isValid = c.validateFormat7Settings(fmt7imgSet)
    if not isValid:
        print "Format7 settings are not valid!"
        exit()
    c.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket,
                                    fmt7imgSet)
else:
    # spence go for speed. somewhere need to update frame rate option to turn off and free run
    # Check whether pixel format raw8 is supported
    if PyCapture2.PIXEL_FORMAT.RAW8 & fmt7info.pixelFormatBitField == 0:
        print "Pixel format is not supported\n"
        exit()

    # Configure camera format7 settings
예제 #9
0
파일: camera.py 프로젝트: Foztarz/bb_wdd2
    def __init__(self,
                 height,
                 width,
                 fps,
                 device,
                 subsample=0,
                 fullframe_path=None,
                 gain=100,
                 cam_identifier=None,
                 start_timestamp=None,
                 roi=None):
        super().__init__(height,
                         width,
                         fps=fps,
                         subsample=subsample,
                         fullframe_path=fullframe_path,
                         cam_identifier=cam_identifier,
                         start_timestamp=start_timestamp,
                         roi=roi)

        self.device = device

        bus = PyCapture2.BusManager()
        numCams = bus.getNumOfCameras()

        print(10 * "*" + " AVAILABLE CAMERAS " + 10 * "*")
        for i in range(numCams):
            print("\n{})".format(i + 1))
            self.cap = PyCapture2.Camera()
            self.uid = bus.getCameraFromIndex(i)
            self.cap.connect(self.uid)
            self.print_cam_info(self.cap)
            self.cap.disconnect()

            bus = PyCapture2.BusManager()

        if not numCams:
            raise RuntimeError("No Flea3 camera detected")

        self.cap = PyCapture2.Camera()
        self.uid = bus.getCameraFromSerialNumber(int(device))
        self.cap.connect(self.uid)

        print(10 * "*" + " SELECTED CAMERA " + 10 * "*")
        self.print_cam_info(self.cap)

        fmt7imgSet = PyCapture2.Format7ImageSettings(
            PyCapture2.MODE.MODE_4, 0, 0, 2048, 1080,
            PyCapture2.PIXEL_FORMAT.MONO8)
        fmt7pktInf, isValid = self.cap.validateFormat7Settings(fmt7imgSet)
        if not isValid:
            raise RuntimeError("Format7 settings are not valid!")

        self.cap.setFormat7ConfigurationPacket(
            fmt7pktInf.recommendedBytesPerPacket, fmt7imgSet)

        self.cap.setProperty(type=PyCapture2.PROPERTY_TYPE.FRAME_RATE,
                             absValue=fps)
        self.cap.setProperty(type=PyCapture2.PROPERTY_TYPE.AUTO_EXPOSURE,
                             absValue=False)
        self.cap.setProperty(type=PyCapture2.PROPERTY_TYPE.SHUTTER,
                             absValue=1 / fps * 1000)
        self.cap.setProperty(type=PyCapture2.PROPERTY_TYPE.GAIN, absValue=100)

        self.cap.startCapture()
예제 #10
0
# Select camera on 0th index
c = PyCapture2.Camera()
c.connect(bus.getCameraFromIndex(0))

# Print camera details
print_camera_info(c)
fmt7_info, supported = c.getFormat7Info(0)
print_format7_capabilities(fmt7_info)

# Check whether pixel format mono8 is supported
if PyCapture2.PIXEL_FORMAT.MONO8 & fmt7_info.pixelFormatBitField == 0:
    print('Pixel format is not supported\n')
    exit()

# Configure camera format7 settings
fmt7_img_set = PyCapture2.Format7ImageSettings(0, 0, 0, fmt7_info.maxWidth, fmt7_info.maxHeight, PyCapture2.PIXEL_FORMAT.MONO8)
fmt7_pkt_inf, isValid = c.validateFormat7Settings(fmt7_img_set)
if not isValid:
    print('Format7 settings are not valid!')
    exit()
c.setFormat7ConfigurationPacket(fmt7_pkt_inf.recommendedBytesPerPacket, fmt7_img_set)

# Enable camera embedded timestamp
enable_embedded_timestamp(c, True)

print('Starting image capture...')
c.startCapture()
grab_images(c, 10)
c.stopCapture()

# Disable camera embedded timestamp
예제 #11
0
bus = PyCapture2.BusManager()
numCams = bus.getNumOfCameras()
print "Number of cameras detected: ", numCams
if not numCams:
    print "Insufficient number of cameras. Exiting..."
    exit()

# Select camera on 0th index
c = PyCapture2.Camera()
uid = bus.getCameraFromIndex(0)
c.connect(uid)
printCameraInfo(c)

fmt7info, supported = c.getFormat7Info(0)

fmt7imgSet = PyCapture2.Format7ImageSettings(0, 700, 400, 1040, 1000,
                                             PyCapture2.PIXEL_FORMAT.MONO8)

fmt7pktInf, isValid = c.validateFormat7Settings(fmt7imgSet)

if not isValid:
    print "Format7 settings are not valid!"
    exit()

c.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket,
                                fmt7imgSet)

print "Starting image capture..."

c.startCapture()

image = c.retrieveBuffer()
예제 #12
0
powerVal = 0x80000000

c.writeRegister(cameraPower, powerVal)


# Configure trigger mode
triggerMode = c.getTriggerMode()
triggerMode.onOff = True
triggerMode.mode = 0
triggerMode.parameter = 0
triggerMode.source = 7		# Using software trigger

c.setTriggerMode(triggerMode)

# Configure camera format7 settings
fmt7imgSet = PyCapture2.Format7ImageSettings(0, 0, 0, 1920, 1080, PyCapture2.PIXEL_FORMAT.RAW8)
fmt7pktInf, isValid = c.validateFormat7Settings(fmt7imgSet)
if not isValid:
	print("Format7 settings are not valid!")
	exit()

c.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket, fmt7imgSet)

pollForTriggerReady(c)

c.setConfiguration(grabTimeout = 5000)

# Start acquisition

c.startCapture()
예제 #13
0
    def _cam_init(self,set_gpio=True):
        self.bus = pc2.BusManager()
        self.cam = pc2.Camera()
        if not self.bus.getNumOfCameras():
            display('No Point Grey Research cameras detected')
            raise
        # Run example on the first camera
        uid = self.bus.getCameraFromIndex(self.cam_id)
        self.cam.connect(uid)
        embedded_info = self.cam.getEmbeddedImageInfo()
        if embedded_info.available.timestamp:
            self.cam.setEmbeddedImageInfo(timestamp = True)
            enable_timestamp = True
        if enable_timestamp:
            display('[PointGrey] - timestamp is enabled.')
        else:
            display('[PointGrey] - timeStamp is disabled.') 
        fmt7_info, supported = self.cam.getFormat7Info(0)
        if supported:
            display('[PointGrey] - Max image pixels: ({}, {})'.format(
                fmt7_info.maxWidth, fmt7_info.maxHeight))
            if not len(self.roi):
                self.roi = [0,0,fmt7_info.maxWidth,fmt7_info.maxHeight]
            display('[PointGrey] - Image unit size: ({}, {})'.format(
                fmt7_info.imageHStepSize, fmt7_info.imageVStepSize))
            display('[PointGrey] - Offset unit size: ({}, {})'.format(
                fmt7_info.offsetHStepSize, fmt7_info.offsetVStepSize))
            #display('[PointGrey] - Pixel format bitfield: 0x{}'.format(
            #    fmt7_info.pixelFormatBitField))
            #if pc2.PIXEL_FORMAT.MONO8 & fmt7_info.pixelFormatBitField == 0:
            #    display('[PointGrey] - setting MONO8')
            x,y,w,h = self.roi
            fmt7_img_set = pc2.Format7ImageSettings(0,x, y,w,h,
                                                    pc2.PIXEL_FORMAT.MONO8)
            fmt7_pkt_inf, isValid = self.cam.validateFormat7Settings(fmt7_img_set)
            if not isValid:
                print('[PointGrey] - Format7 settings are not valid!')
            self.cam.setFormat7ConfigurationPacket(fmt7_pkt_inf.recommendedBytesPerPacket, fmt7_img_set)
        tmp = self.cam.getProperty(pc2.PROPERTY_TYPE.FRAME_RATE)
        tmp.absValue = self.frame_rate
        tmp.onOff = True
        self.cam.setProperty(tmp)
        tmp = self.cam.getProperty(pc2.PROPERTY_TYPE.FRAME_RATE)
        self.frame_rate = tmp.absValue
        display('[PointGrey] - Frame rate is:{0}'.format(self.frame_rate))
        # Set gain
        tmp = self.cam.getProperty(pc2.PROPERTY_TYPE.GAIN)
        tmp.absValue = self.gain
        tmp.onOff = True
        self.cam.setProperty(tmp)
        #start communication
        #self.cam.open_device()
        #self.cam.set_acq_timing_mode('XI_ACQ_TIMING_MODE_FREE_RUN')
        #self.cam.set_exposure(self.exposure)
        #self.cam.set_binning_vertical(self.binning)
        #self.cam.set_binning_horizontal(self.binning)
        # Set the GPIO
        #self.cam.set_gpi_selector('XI_GPI_PORT1')
        #self.cam.set_trigger_source('XI_TRG_OFF')

        #if set_gpio:
        #    self.cam.set_gpo_selector('XI_GPO_PORT1')
            # for now set the GPO to blink in software (port1 will do that for sync purposes, the test cam does not support XI_GPO_EXPOSURE_PULSE)
        #    self.cam.set_gpo_mode('XI_GPO_ON'); #XI_GPO_EXPOSURE_PULSE
        #    if self.triggered.is_set():
        #        self.cam.set_gpi_mode('XI_GPI_TRIGGER')
        #        self.cam.set_trigger_source('XI_TRG_EDGE_RISING')
        self.lastframeid = -1
        self.nframes.value = 0
        self.camera_ready.set()
        self.prev_ts = 0
        self.lasttime = time.time()
예제 #14
0
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()
예제 #15
0
from gi.repository import Gtk, Gdk, GdkPixbuf, GLib

# Ensure sufficient cameras are found
bus = PyCapture2.BusManager()

# Select camera on 0th index
c = PyCapture2.Camera()
uid = bus.getCameraFromIndex(0)
# uid = bus.getCameraFromSerialNumber(17023355)
c.connect(uid)

# Configure camera format7 settings
fmt7info, supported = c.getFormat7Info(0)
# fmt7imgSet = PyCapture2.Format7ImageSettings(0, 0, 0, fmt7info.maxWidth, fmt7info.maxHeight, PyCapture2.PIXEL_FORMAT.RGB)
fmt7imgSet = PyCapture2.Format7ImageSettings(PyCapture2.MODE.MODE_0, 0, 0,
                                             fmt7info.maxWidth,
                                             fmt7info.maxHeight,
                                             PyCapture2.PIXEL_FORMAT.RGB)
fmt7pktInf, isValid = c.validateFormat7Settings(fmt7imgSet)
if not isValid:
    print("Format7 settings are not valid!")
    exit()

c.setFormat7ConfigurationPacket(fmt7pktInf.recommendedBytesPerPacket,
                                fmt7imgSet)

# Capture a frame for testing
c.startCapture()

# GUI initialisation
window = Gtk.Window()
window.set_title("RIP")
    def __init__(self, serial_number):
        """Initialize FlyCapture2 API camera.
        
        Searches all cameras reachable by the host using the provided serial
        number. Fails with API error if camera not found.
        
        This function also does a significant amount of default configuration.
        
        * It defaults the grab timeout to 1 s
        * Ensures use of the API's HighPerformanceRetrieveBuffer
        * Ensures the camera is in Format 7, Mode 0 with full frame readout and MONO8 pixels
        * If using a GigE camera, automatically maximizes the packet size and warns if Jumbo packets are not enabled on the NIC
        
        Args:
            serial_number (int): serial number of camera to connect to
        """

        global PyCapture2
        import PyCapture2

        ver = PyCapture2.getLibraryVersion()
        min_ver = (2, 12, 3, 31)  # first release with python 3.6 support
        if ver < min_ver:
            raise RuntimeError(
                f"PyCapture2 version {ver} must be >= {min_ver}")

        print('Connecting to SN:%d ...' % serial_number)
        bus = PyCapture2.BusManager()
        self.camera = PyCapture2.Camera()
        self.camera.connect(bus.getCameraFromSerialNumber(serial_number))

        # set which values of properties to return
        self.get_props = [
            'present', 'absControl', 'absValue', 'onOff', 'autoManualMode',
            'valueA', 'valueB'
        ]

        fmts = {
            prop: getattr(PyCapture2.PIXEL_FORMAT, prop)
            for prop in dir(PyCapture2.PIXEL_FORMAT)
            if not prop.startswith('_')
        }

        self.pixel_formats = IntEnum('pixel_formats', fmts)

        self._abort_acquisition = False

        # check if GigE camera. If so, ensure max packet size is used
        cam_info = self.camera.getCameraInfo()
        if cam_info.interfaceType == PyCapture2.INTERFACE_TYPE.GIGE:
            # need to close generic camera first to avoid strange interactions
            print('Checking Packet size for GigE Camera...')
            self.camera.disconnect()
            gige_camera = PyCapture2.GigECamera()
            gige_camera.connect(bus.getCameraFromSerialNumber(serial_number))
            mtu = gige_camera.discoverGigEPacketSize()
            if mtu <= 1500:
                msg = """WARNING: Maximum Transmission Unit (MTU) for ethernet 
                NIC FlyCapture2_Camera SN:%d is connected to is only %d. 
                Reliable operation not expected. 
                Please enable Jumbo frames on NIC."""
                print(dedent(msg % (serial_number, mtu)))

            gige_pkt_size = gige_camera.getGigEProperty(
                PyCapture2.GIGE_PROPERTY_TYPE.GIGE_PACKET_SIZE)
            # only set if not already at correct value
            if gige_pkt_size.value != mtu:
                gige_pkt_size.value = mtu
                gige_camera.setGigEProperty(gige_pkt_size)
                print('  Packet size set to %d' % mtu)
            else:
                print('  GigE Packet size is %d' % gige_pkt_size.value)

            # close GigE handle to camera, re-open standard handle
            gige_camera.disconnect()
            self.camera.connect(bus.getCameraFromSerialNumber(serial_number))

        # set standard device configuration
        config = self.camera.getConfiguration()
        config.grabTimeout = 1000  # in ms
        config.highPerformanceRetrieveBuffer = True
        self.camera.setConfiguration(config)

        # ensure camera is in Format7,Mode 0 custom image mode
        fmt7_info, supported = self.camera.getFormat7Info(0)
        if supported:
            # to ensure Format7, must set custom image settings
            # defaults to full sensor size and 'MONO8' pixel format
            print('Initializing to default Format7, Mode 0 configuration...')
            fmt7_default = PyCapture2.Format7ImageSettings(
                0, 0, 0, fmt7_info.maxWidth, fmt7_info.maxHeight,
                self.pixel_formats['MONO8'].value)
            self._send_format7_config(fmt7_default)

        else:
            msg = """Camera does not support Format7, Mode 0 custom image
            configuration. This driver is therefore not compatible, as written."""
            raise RuntimeError(dedent(msg))
예제 #17
0
    def CameraSetup(self, framerate, exposure):
        bus = self.BusSetup()
        # Select camera on 0th index
        self.camera = PyCapture2.Camera()
        c = self.camera
        c.connect(bus.getCameraFromIndex(0))

        # Print camera details
        self.printCameraInfo(c)
        fmt7info, supported = c.getFormat7Info(0)
        self.printFormat7Capabilities(fmt7info)

        # See the pdf, use PROPERTY, and PROPERTY_TYPE, to set shutter.
        # Set video mode to format 7, raw8
        # Set height to reduced that is acceptable
        # Ensure frame rate if FORMAT7
        # go to town.
        # test by reseting camera and ensure code resets it, not flycap.

        if 0:
            # Check whether pixel format mono8 is supported
            if PyCapture2.PIXEL_FORMAT.MONO8 & fmt7info.pixelFormatBitField == 0:
                print "Pixel format is not supported\n"
                exit()

# Configure camera format7 settings
            fmt7imgSet = PyCapture2.Format7ImageSettings(
                0, 0, 0, fmt7info.maxWidth, fmt7info.maxHeight,
                PyCapture2.PIXEL_FORMAT.MONO8)
            fmt7pktInf, isValid = c.validateFormat7Settings(fmt7imgSet)
            if not isValid:
                print "Format7 settings are not valid!"
                exit()
            c.setFormat7ConfigurationPacket(
                fmt7pktInf.recommendedBytesPerPacket, fmt7imgSet)
        else:
            # spence go for speed. somewhere need to update frame rate option to turn off and free run
            # Check whether pixel format raw8 is supported
            if PyCapture2.PIXEL_FORMAT.RAW8 & fmt7info.pixelFormatBitField == 0:
                print "Pixel format is not supported\n"
                exit()

# Configure camera format7 settings
            fmt7imgSet = PyCapture2.Format7ImageSettings(
                0, 0, 0, fmt7info.maxWidth, 512, PyCapture2.PIXEL_FORMAT.RAW8)
            fmt7pktInf, isValid = c.validateFormat7Settings(fmt7imgSet)
            if not isValid:
                print "Format7 settings are not valid!"
                exit()
            c.setFormat7ConfigurationPacket(
                fmt7pktInf.recommendedBytesPerPacket, fmt7imgSet)

    #control frame rate
        c.setProperty(type=PyCapture2.PROPERTY_TYPE.FRAME_RATE,
                      autoManualMode=False)
        c.setProperty(type=PyCapture2.PROPERTY_TYPE.AUTO_EXPOSURE,
                      autoManualMode=False)
        c.setProperty(type=PyCapture2.PROPERTY_TYPE.FRAME_RATE,
                      absValue=framerate)
        c.setProperty(type=PyCapture2.PROPERTY_TYPE.AUTO_EXPOSURE,
                      absValue=exposure)
        return c