def __init__(self, resolution = (320, 240)): """ Create a new instance of a PTCamera which uses PyCapture2's GigECamera API Parameters ---------- resolution: tuple of ints; default: (320, 240) Resolution of desired input video stream; default is 320x240 which will make sure the camera initialization will not error out regardless of the capture mode selected. """ #self._update_count = 0 # Ensure sufficient cameras are found bus = PyCapture2.BusManager() num_cams = bus.getNumOfCameras() print('Number of cameras detected: ', num_cams) if not num_cams: print('Insufficient number of cameras. Exiting...') exit() # Select camera on 0th index self.c = PyCapture2.GigECamera() uid = bus.getCameraFromIndex(0) self.c.connect(uid) self.initialize_camera_settings(resolution) print('Starting image capture...') self.c.startCapture() self._frame_req = True
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()
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()
def init_cam(self): # 1. Start the bus interface # 2. Connect to the camera and start capturin # often the camera throws a bus master failure in the first and a isochronous start failure # in the second connection attempt. These are supposed to be caught in the following. for i in range(100): print("detect bus") try: print("init cam") bus = pc2.BusManager() # test code cams = bus.discoverGigECameras(10) print(cams) # end test code bus.forceAllIPAddressesAutomatically( ) # necessary due to my networking inabilities cam = pc2.GigECamera() cam.connect( bus.getCameraFromSerialNumber( camera_serial_numbers[camera_index])) # set up camera for GigE use gigeconf = cam.getGigEConfig() gigeconf.enablePacketResend = True cam.setGigEConfig(gigeconf) # set up configuration of camera conf = cam.getConfiguration() conf.numBuffers = 4 conf.grabTimeout = self.acquisition_timer_interval conf.grabMode = 1 # BUFFER_FRAMES grab mode, see docs cam.setConfiguration(conf) # start streaming cam.startCapture() time.sleep(.1) print("Started stream for cam {0}".format( camera_serial_numbers[camera_index])) except pc2.Fc2error as e: try: cam.disconnect() except: pass del cam, bus print(e) print("Retrying 1...") else: break self.cam = cam # 3. collect framerates, videomodes, ... fr = pc2.FRAMERATE self.framerates = [f for f in dir(fr) if not f.startswith('__')] vm = pc2.VIDEO_MODE self.video_modes = [v for v in dir(vm) if not v.startswith('__')]
def initRealtimeCamera(): # set camera bus = PyCapture2.BusManager() cam = PyCapture2.Camera() uid = bus.getCameraFromIndex(0) cam.connect(uid) cam.startCapture() return cam
def __init__(self,camIndex=0): """this is all the stuff you need to do to initialize the camera. It should work for multiple cameras as long as you change the camIndex""" bus = PyCapture2.BusManager() numCams = bus.getNumOfCameras() self.camera = PyCapture2.Camera() uid = bus.getCameraFromIndex(0) self.camera.connect(uid) self.camera.startCapture()
def initialize_camera(index): """ Initializes a PT Grey camera by its enumerated index, and returns the camera instance :return: A camera instance representing the camera and its controls. """ bus = PyCapture2.BusManager() camera = PyCapture2.Camera() uid = bus.getCameraFromIndex(index) camera.connect(uid) configure_camera(camera) camera.startCapture() return camera
def __init__(self, camera_id): try: self.bus = PyCapture2.BusManager() self.num_cams = self.bus.getNumOfCameras() self.camera = PyCapture2.Camera() self.uid = self.bus.getCameraFromIndex(camera_id) self.camera.connect(self.uid) self.print_build_info() self.print_camera_info() except Exception as e: print(e) print('Could not load camera, will now exit.') exit()
def main(): 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 cam = PyCapture2.Camera() uid = bus.getCameraFromIndex(0) cam.connect(uid) RR.RobotRaconteurNode.s.NodeName = "OverheadCam" overheadCam = overheadCam_imp(cam) t = RR.TcpTransport() t.StartServer(5885) RR.RobotRaconteurNode.s.RegisterTransport(t) updateMarkers = threading.Thread(target=detectMarkers, args=(overheadCam, )) updateMarkers.setDaemon(True) updateMarkers.start() try: with open('overheadCamServiceFast.robdef', 'r') as f: service_def = f.read() except: print("error1") try: RR.RobotRaconteurNode.s.RegisterServiceType(service_def) except: print("error2") try: RR.RobotRaconteurNode.s.RegisterService("ohcam", "edu.rpi.camService.ohcam", overheadCam) print("Connect at tcp://localhost:5885/OverheadCam/ohcam") raw_input("press enter to quit...\r\n") except: print("error") RR.RobotRaconteurNode.s.Shutdown() cam.stopCapture() cam.disconnect() cv2.destroyAllWindows()
def __init__(self): """Initialise the PyCapture2 Camera.""" self.busManager = PyCapture2.BusManager() self.camera = PyCapture2.Camera() # Temporary buffer self.buffer = None self.callback = None # Declare camera modes here self.mode_current = None self.mode_default = None self.mode_focus = None self.mode_capture = None
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)
def save_video_helper(cam, file_format, filename, framerate): num_images = 200 video = PyCapture2.FlyCapture2Video() for i in range(num_images): print('index ', i) try: print("before retrievebuffer") image = cam.retrieveBuffer() print("after retrievebuffer") except PyCapture2.Fc2error as fc2Err: print('Error retrieving buffer : %s' % fc2Err) continue print('Grabbed image {}'.format(i)) if (i == 0): if file_format == 'AVI': video.AVIOpen(filename, framerate) elif file_format == 'MJPG': video.MJPGOpen(filename, framerate, 75) elif file_format == 'H264': video.H264Open(filename, framerate, image.getCols(), image.getRows(), 1000000) else: print('Specified format is not available.') return video.append(image) print('Appended image %d...' % i) print('Appended {} images to {} file: {}...'.format( num_images, file_format, filename)) video.close()
def __init__(self): super(cameraBase, self).__init__() self.camera = PyCapture2.Camera() self.running = False self.readyCapture = False self.mode = self.VIDEO_MODE
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 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
def bind(self, ret_form_id, bindings=None): self.CAMpayload = bindings[0] self.CAMwide = bindings[1] self.ret_form_id = ret_form_id self.info = [] # Buttons self.butPayload = bs.add_button(self, self.CAMpayload.name, self.on_displayPayload) self.butWide = bs.add_button(self, self.CAMwide.name, self.on_displayWide, prevButton=self.butPayload) # Payload Camera Info self.camInfoPayload = bs.add_text_mult(self, "Camera Information", rows=8) self.on_displayPayload() # Py Capture version libVer = PyCapture2.getLibraryVersion() self.pyCaptureInfo = "PyCapture2 library version " + str( libVer[0]) + "." + str(libVer[1]) + "." + str(libVer[3]) self.pyCaptureInfoDisp = bs.add_text(self, "Py Capture Information", value=self.pyCaptureInfo)
def __init__(self, camera_id=0, bus_manager=None): if bus_manager is None: bus_manager = PyCapture2.BusManager() self.busman = bus_manager if camera_id is not None: self.Connect(camera_id=camera_id)
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
def initialize(self): # Initialize video capture # 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..." self.exit() # Select camera on 0th index self.c = PyCapture2.Camera() uid = bus.getCameraFromIndex(0) self.c.connect(uid) printCameraInfo(self.c) print "Starting image capture..."
def listAvailableModes(cam_num=None, cam=None, bus=None): """ List valid video modes and framerates for specified camera. Parameters ---------- cam_num : int, optional Index of camera to connect to. Cannot be specified alongside <cam>, and must be specified if <cam> is not. cam : PyCapture2.Camera instance, optional Handle to camera connection. Cannot be specified alongisde <cam_num>, and must be specified if <cam_num> is not. bus : PyCapture2.BusManager instance, optional Only relevant if <cam> is None / <cam_num> is not None. Bus manager to connect camera. If None (default), one will be created. Returns ------- res : list List of (mode, framerate) tuples giving all valid options. """ # Ensure one of cam_num or cam is specified if cam_num is None and cam is None: raise ValueError('Must specify cam_num or cam') elif cam_num is not None and cam is not None: raise ValueError('Can only specify one of cam_num or cam') # If no cam given, create one from index. Also create bus if needed. if cam is None: cam = PyCapture2.Camera() if bus is None: bus = PyCapture2.BusManager() cam.connect(bus.getCameraFromIndex(cam_num)) # Find and return compatible modes res = [] for modename, modeval in VIDEO_MODES.items(): for ratename, rateval in FRAMERATES.items(): try: if cam.getVideoModeAndFrameRateInfo(modeval, rateval): res.append((modename, ratename)) except: pass return res
def initializeCamera(self, index=0): """ Initializes the camera. :return: """ # get camera guid to control it self.bus = PyCapture2.BusManager() guid = self.bus.getCameraFromIndex(index) self.camera.connect(guid)
def getPortInfo(): # Ensure sufficient cameras are found bus = PyCapture2.BusManager() num_cams = bus.getNumOfCameras() camera_infos = [] print('Number of cameras detected: ', num_cams) if not num_cams: print('Insufficient number of cameras. Exiting...') return None for i in range(num_cams): camera_guid = bus.getCameraFromIndex(i) camera = PyCapture2.Camera() camera.connect(camera_guid) serial_num, model_name = Chameleon.get_camera_info(camera) camera_infos.append("{}&{}&{}".format(str(model_name), serial_num, i)) camera.disconnect() return camera_infos
def BusSetup(self): # 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() return bus
def __init__(self): # Print PyCapture2 Library Information print_build_info() # Ensure sufficient cameras are found self.bus = PyCapture2.BusManager() self.num_cams = self.bus.getNumOfCameras() print('Number of cameras detected: %d' % self.num_cams) if self.num_cams <= 0: print('Insufficient number of cameras. Exiting...') exit()
def connect_led_camera(): print("\n***** CONNECTING TO FIBREHEAD LED CAMERA *****") bus = pc2.BusManager() numCams = bus.getNumOfCameras() if numCams == 0: print("\n***** COULD NOT CONNECT TO FIBREHEAD LED CAMERA ******\n") return None else: camera = Camera(bus) print("\n***** FINISHED CONNECTING TO FIBREHEAD LED CAMERA *****\n") return camera
def setup_camera(): bus = PyCapture2.BusManager() num_cams = bus.getNumOfCameras() logging.info('Number of cameras detected: %d' % num_cams) if not num_cams: logging.error('Insufficient number of cameras. Exiting...') raise ValueError('Insufficient number of cameras. Exiting...') cam = PyCapture2.Camera() cam.connect(bus.getCameraFromIndex(0)) cam_info = cam.getCameraInfo() logging.info('*** CAMERA INFORMATION ***') logging.info('Serial number - %d', cam_info.serialNumber) logging.info('Camera model - %s', cam_info.modelName) logging.info('Camera vendor - %s', cam_info.vendorName) logging.info('Sensor - %s', cam_info.sensorInfo) logging.info('Resolution - %s', cam_info.sensorResolution) logging.info('Firmware version - %s', cam_info.firmwareVersion) logging.info('Firmware build time - %s', cam_info.firmwareBuildTime) cam.startCapture() return cam
def setExposure(self, exposureVale): if self.running: self.stopAcquisition() self.readyCapture = False exposure = PyCapture2.Property() exposure.type = PyCapture2.PROPERTY_TYPE.AUTO_EXPOSURE exposure.onOff = True exposure.autoManualMode = False exposure.absControl = True exposure.absValue = exposureVale self.camera.setProperty(exposure) self.readyCapture = True
def run(self): bus = PyCapture2.BusManager() uid = bus.getCameraFromIndex(0) c = PyCapture2.Camera() c.connect(uid) while True: c.startCapture() img = c.retrieveBuffer() c.stopCapture() cv_img1 = np.array(img.getData(), dtype="uint8").reshape( (img.getRows(), img.getCols())) cv_img = cv2.cvtColor(cv_img1, cv2.COLOR_BAYER_BG2BGR) cv_img = cv2.resize(cv_img, (380, 270)) height, width, dim = cv_img.shape bytesPerLine = dim * width image = QtGui.QImage(cv_img.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) self.imageChanged.emit(image)
def __init__(self, width=720, height=480): self.width = width self.height = height #Connect to Camera bus = PyCapture2.BusManager() camInfo = bus.discoverGigECameras() self.cam = PyCapture2.GigECamera() uID = bus.getCameraFromIndex(0) self.cam.connect(uID) #Set Up Camera Parameters imgSetInfo = self.cam.getGigEImageSettingsInfo() imgSet = PyCapture2.GigEImageSettings() imgSet.offsetX = (2048 - self.width) / 2 imgSet.offsetY = (2448 - self.height) / 2 imgSet.height = self.height imgSet.width = self.width imgSet.pixelFormat = PyCapture2.PIXEL_FORMAT.RGB self.cam.setGigEImageSettings(imgSet)
def get_cameras(self): """Get all attached blackfly cameras. Populates a list of ethernet cameras: self.available_cameras the list objects are of type: PyCapture2.CameraInfo class @return available_cameras A list of cameras detected which could be connected """ self.bus = PyCapture2.BusManager() # discover at most `max_cameras` cameras on the subnet num_cams = self.settings["max_cameras"] self.available_cameras = self.bus.discoverGigECameras(numCams=num_cams)