Ejemplo n.º 1
0
    def list_available_cameras(self):
        """ Gather serial numbers of online Aravis/Genicam devices.
        :return: a list of serial numbers (as strings). This list may be
                 empty if no cameras are online/switched on.
                 For cameras explicitly addressed by IP, the serial
                 numbers have the format sn@ip, with an @ between number and address.
        :rtype: list

        .. todo:: optionally implement a specific filter for Blackfly's if Basler 
                  cameras should not be listed.
        """

        # Start with (pessimistic) initially empty set of online devices
        serialNums = []
        addrs = []

        # Broadcast ethernet/bus for recognized cameras.
        # Warning/todo: this gathers also cameras that are not of the Blackfly class,
        # and in conjunction with the SDSS may also recognize the Basler cameras..
        Aravis.update_device_list()
        Ndev = Aravis.get_n_devices()
        # print(str(Ndev) + " cameras online")

        # get_device_id returns a string of type, SN, MAC etc
        for i in range(Ndev):
            cam = Aravis.Camera.new(Aravis.get_device_id(i))
            uid = cam.get_string("DeviceSerialNumber")
            serialNums.append(uid)
            addrs.append('')

        # Try to ping cameras explicitly proposed with ctor.
        for ip in self.ips_nonlocal:
            try:
                cam = Aravis.Camera.new(ip)
                uid = cam.get_string("DeviceSerialNumber")
                # If is this was already in the scan: discard, else add
                if uid not in serialNums:
                    serialNums.append(uid)
                    addrs.append('@' + ip)
            except:
                # apparently no such camera at this address....
                pass

        # we zip the two lists to the format 'serialnumber{@ip}'
        ids = []
        for cam in range(len(serialNums)):
            ids.append(serialNums[cam] + addrs[cam])

        return ids
def getCameraStream():
    Aravis.enable_interface("Fake")

    try:
        if len(sys.argv) > 1:
            camera = Aravis.Camera.new(sys.argv[1])
        else:
            camera = Aravis.Camera.new(None)
    except:
        print("No camera found")
        exit()

    stream = camera.create_stream(None, None)

    #stream.push_buffer (Aravis.Buffer.new_allocate(payload))

    return stream, camera
Ejemplo n.º 3
0
    def __init__(self):
        # Open camera, and get image dimensions
        Aravis.enable_interface('Fake')
        self.camera = Aravis.Camera.new(None)
        self.stream = self.camera.create_stream(None, None)
        payload = self.camera.get_payload()
        self.stream.push_buffer(Aravis.Buffer.new_allocate(payload))
        x, y, w, h = self.camera.get_region()
        self.width = w
        self.height = h
        self.camera.start_acquisition()

        # Set up scanner
        self.scanner = zbar.ImageScanner()
        self.scanner.parse_config('enable')

        # Set up code cache
        self.cache = {}
Ejemplo n.º 4
0
'''

#--- Set conversion mode, gain, exposure time here:

GCM = "HCG"  # Gain Conversion Mode ("HCG" or "LCG")
GainSetting = 5.0  # Gain setting 0-48
ExpTime = 0.07  # Exposure time (Seconds: 18E-6 to 30)

cam.set_string('GainConversion', GCM)  # Set gain conversion mode
cam.set_gain(GainSetting)  #   and Gain Setting
cam.set_exposure_time(ExpTime * 1.0E6)  # Exposure time (uSec)

#---

cam.set_acquisition_mode((Aravis.acquisition_mode_from_string('SingleFrame')
                          ))  # Set to single frames

cam.set_boolean('ReverseX', False)  # Use these to flip left-right
cam.set_boolean('ReverseY', False)  #   and up-down

# cam.set_string('ImageCompressionMode','Off')           # Definitely don't want this (WRITE-PROTECTED?)
cam.set_string('AdcBitDepth', 'Bit12')  # Only option for this camera
cam.set_string('DeviceTemperatureSelector',
               'Sensor')  # Only option for this camera

cam.set_boolean('DefectCorrectStaticEnable',
                False)  # Turn off auto-correction of (known) bad pixels

dev = cam.get_device()  # Allows access to "deeper" features
Ejemplo n.º 5
0
def worker(camId):
    pyyolo.init(darknet_path, datacfg, cfgfile, weightfile)
    Aravis.enable_interface("Fake")
    try:
        cam = Aravis.Camera.new(camId)
        print("Camera found")
    except:
        print("No camera found")
        exit()

    thresh = 0.45
    hier_thresh = 0.5

    #cam.set_region (0,0,2048,1536)
    #cam.set_region (0,0,512,512)
    #cam.set_frame_rate (10.0)
    #cam.set_exposure_time(500000)
    #cam.set_pixel_format (Aravis.PIXEL_FORMAT_MONO_8)

    #print(dir(cam))

    stream = cam.create_stream(None, None)

    payload = cam.get_payload()

    [x, y, width, height] = cam.get_region()

    print("Camera vendor : %s" % (cam.get_vendor_name()))
    print("Camera model  : %s" % (cam.get_model_name()))
    print("Camera id     : %s" % (cam.get_device_id()))
    print("ROI           : %dx%d at %d,%d" % (width, height, x, y))
    print("Payload       : %d" % (payload))
    print("Pixel format  : %s" % (cam.get_pixel_format_as_string()))

    #cv2.namedWindow('Live Stream', flags=0)
    cv2.namedWindow(camId, flags=0)

    #rint(dir(stream))

    #for i in range(0,50):
    #stream.push_buffer (Aravis.Buffer.new_allocate (payload))

    cam.start_acquisition()

    lastTime = time.time()
    transposeTime = 0
    i = 0

    while (True):
        stream.push_buffer(Aravis.Buffer.new_allocate(payload))
        buffer = stream.pop_buffer()
        transposeTime = time.time()
        b = ctypes.cast(buffer.data, ctypes.POINTER(ctypes.c_uint8))
        im = np.ctypeslib.as_array(b, (height, width))
        #im = im.copy()
        #print("shape: ", im.shape)
        #cv2.imshow("Live Stream", im.copy())
        gray = im.copy()
        cv2.imshow(camId, gray)
        #im = np.zeros((3,gray.shape[0],gray.shape[1]))
        #im[1,:,:] = gray
        #im = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
        im = np.stack((im, ) * 3, -1)
        im = im.transpose(2, 0, 1)
        c, h, w = im.shape[0], im.shape[1], im.shape[2]
        #print(im.shape)
        #cv2.imshow(camId, im.copy())
        im = im.ravel() / 255.0
        #print(im.shape)
        data = np.ascontiguousarray(im, dtype=np.float32)
        #print("TRANS-FPS: ", 1.0/(time.time()-transposeTime))
        predictions = pyyolo.detect(w, h, c, data, thresh, hier_thresh)
        # { 'left':0, 'right': 767, 'top': 0, 'bottom': x, class': x, prob: x, }
        for output in predictions:
            left, right, top, bottom, what, prob = output['left'], output[
                'right'], output['top'], output['bottom'], output[
                    'class'], output['prob']
            print(output)
            if (what == 'car'):
                d_from_top = top
                d_from_bottom = bottom
                d_from_left = left
                d_from_right = right
                d_height = top
                d_width = left
                if (d_height > 0.5):
                    print(output)
                    #trigger other cameras
        cv2.waitKey(1)
        print("CAM: ", camId, " Frame: ", i, " FPS: ",
              1.0 / (time.time() - lastTime), "RES: ", h, " x ", w)
        lastTime = time.time()
        i += 1
    cam.stop_acquisition()
Ejemplo n.º 6
0
import gi
gi.require_version('Aravis', '0.6')
from gi.repository import Aravis
cam = Aravis.Camera()
dev = cam.get_device()
ps = dev.get_integer_feature_value('GevSCPSPacketSize')
print('Packet size:', ps)
Ejemplo n.º 7
0
    print("Gain Conv.    : ",cam.get_string('GainConversion'))
    print("Gain Setting  : ",cam.get_gain())
    print("Exposure time : %s seconds " %(cam.get_exposure_time()/1.0E6))
    print("")



fakeCam = False   # Whether to use the Aravis "fake" camera (software) instead of the FLIR
verbose = True    # How wordy to be

print ("-----")

gi.require_version('Aravis', '0.8')
from gi.repository import Aravis

Aravis.update_device_list()

if fakeCam:
    Aravis.enable_interface("Fake")    # using arv-fake-gv-camera-0.8
    cam = Aravis.Camera.new(None)      # Instantiate cam
    print ("Instantiated cam with arv-fake-gv-camera-0.8")

else:             # Note: We expect only one "real"camera

    try:
      cam = Aravis.Camera.new(Aravis.get_device_id(0))      # Instantiate cam
      print ("Instantiated cam with FLIR")
    except:
      print("No camera found")
      exit()
Ejemplo n.º 8
0
def get_device_ids():
    n = Aravis.get_n_devices()
    l = [Aravis.get_device_id(i) for i in range(0, n)]
    return l
def get_device_ids():
    Aravis.update_device_list()
    n = Aravis.get_n_devices()
    return [Aravis.get_device_id(i) for i in range(0, n)]
Ejemplo n.º 10
0
print("ROI           : %dx%d at %d,%d" % (width, height, x, y))
print("Pixel format  : %s" % (cam.get_pixel_format_as_string()))
print("Frame size     : %d  Bytes" % (payload))

print("")
print("Framerate     : %s Hz" % (cam.get_frame_rate()))
print("Exposure time : %s seconds " % (cam.get_exposure_time() / 1.0E6))
print("Gain Conv.    : ", cam.get_string('GainConversion'))
print("Gamma enable  : ", cam.get_boolean('GammaEnable'))
print("Gamma value   : ", cam.get_float('Gamma'))

print("")
print("Available Formats : ",
      cam.dup_available_pixel_formats_as_display_names())
print("acquisition_mode ",
      Aravis.acquisition_mode_to_string(cam.get_acquisition_mode()))
print("framerate bounds ", cam.get_frame_rate_bounds())
print("Exp. Time bounds ", cam.get_exposure_time_bounds())
print("Gain bounds      ", cam.get_gain_bounds())
print("")

print("BlackLevelSelector ", cam.get_string('BlackLevelSelector'))

print("Gain ", cam.get_float('Gain'))
print("BlackLevelClampingEnable ", cam.get_boolean('BlackLevelClampingEnable'))
cam.set_boolean('BlackLevelClampingEnable', False)
print("BlackLevelClampingEnable ", cam.get_boolean('BlackLevelClampingEnable'))

# print ("Features :", cam.dup_available_enumerations_as_strings ())  # Dumps all enumertions

print("GainAuto :",
Ejemplo n.º 11
0
import gi
import os

gi.require_version('Aravis', '0.8')

from gi.repository import Aravis

Aravis.set_fake_camera_genicam_filename(os.getenv('FAKE_GENICAM_PATH'))

Aravis.enable_interface("Fake")

camera = Aravis.Camera.new("Fake_1")

assert camera is not None

camera.set_region(10, 20, 100, 200)
camera.set_frame_rate(50.0)
camera.set_pixel_format(Aravis.PIXEL_FORMAT_MONO_8)

(x, y, w, h) = camera.get_region()

assert x == 10
assert y == 20
assert w == 100
assert h == 200

assert camera.get_pixel_format_as_string() == 'Mono8'

payload = camera.get_payload()

[x, y, width, height] = camera.get_region()
Ejemplo n.º 12
0
    def arg_restrictions():

        Aravis.update_device_list()
        n_cams = Aravis.get_n_devices()
        ids = [Aravis.get_device_id(i) for i in range(n_cams)]
        return {"id": ids}
Ejemplo n.º 13
0
import gi

gi.require_version('Aravis', '0.8')

from gi.repository import Aravis, GLib

Aravis.enable_interface("Fake")

try:
    camera = Aravis.Camera.new("NoCamera")

except TypeError as err:
    pass

camera = Aravis.Camera.new("Fake_1")

try:
    camera.get_integer("Width")
    camera.get_integer("NoFeature")

    assert False  # Not reached

    camera.get_integer("Height")

except GLib.Error as err:
    assert err.matches(Aravis.device_error_quark(),
                       Aravis.DeviceError.FEATURE_NOT_FOUND)

try:
    camera.get_float("NoFeature")
Ejemplo n.º 14
0
    def setup_camera(self):
        print("PROCESS ID: ", os.getpid())
        os.system("sudo chrt -f -p 1 %d" % os.getpid())
        Aravis.enable_interface("Fake")
        self.aravis_camera = Aravis.Camera.new(self.cam_id)
        self.width = int(2048)
        self.height = int(1536)

        self.width = int(2048)
        self.height = int(1536)
        self.aravis_camera.set_binning(1, 1)
        self.aravis_camera.set_region(0, 0, self.width,
                                      self.height)  #2064x1544

        #self.width = int(2048/2)
        #self.height = int(1536/2)
        #self.aravis_camera.set_region(0,0,self.width,self.height) #2064x1544
        #self.aravis_camera.set_binning(2,2)

        self.aravis_camera.gv_set_packet_size(8000)
        self.aravis_camera.gv_set_packet_delay(
            40000)  #np.random.randint(10000))
        print("!!!!")
        print(self.aravis_camera.gv_get_packet_delay())

        #self.aravis_camera.gv_set_stream_options(Aravis.GvStreamOption.NONE)

        aravis_device = self.aravis_camera.get_device()
        ####print(aravis_device.get_string_feature_value('MaxImageSize'))

        availpixelformats = self.aravis_camera.dup_available_pixel_formats_as_strings(
        )

        if 'BayerRG8' in availpixelformats:
            aravis_device.set_string_feature_value("PixelFormat", "BayerRG8")

        #Mono8, RGB8Packed, BayerRG8
        if self.aravis_camera.get_pixel_format_as_string() == 'RGB8Packed':
            print("Colour")
            self.colour_camera = True
        else:
            print("Monochrome")
            self.colour_camera = False

        #Trying to get it working...
        #aravis_device.set_string_feature_value("LineSelector", "Line0")
        #aravis_device.set_string_feature_value("LineMode", "Input")

        #Triggering the camera:
        #  Software trigger...
        #aravis_device.set_string_feature_value("TriggerMode", "On")
        #aravis_device.set_string_feature_value("TriggerSource", "Software")

        #  Hardware trigger...
        aravis_device.set_string_feature_value("TriggerMode", "On")
        aravis_device.set_string_feature_value("TriggerSource", "Line0")

        ##print(aravis_device.get_available_trigger_sources())
        ##print(self.aravis_camera.get_available_pixel_formats_as_strings())
        ##self.aravis_camera.set_trigger("Line0")
        ####### #self.aravis_camera.set_trigger_source("Line0")

        aravis_device.set_string_feature_value("TriggerActivation",
                                               "RisingEdge")
        aravis_device.set_string_feature_value("AcquisitionMode", "Continuous")

        #Triggering the flash...
        #if triggerflash: #this camera might not be the one doing the triggering
        aravis_device.set_string_feature_value("LineSelector", "Line2")
        aravis_device.set_boolean_feature_value("StrobeEnable", True)
        aravis_device.set_string_feature_value("LineMode", "Strobe")
        aravis_device.set_integer_feature_value("StrobeLineDelay", 100)
        aravis_device.set_integer_feature_value("StrobeLinePreDelay",
                                                165)  #200
        aravis_device.set_string_feature_value("LineSource",
                                               "ExposureStartActive")
        aravis_device.set_boolean_feature_value("LineInverter", True)

        #aravis_device.set_string_feature_value("ExposureTimeMode","UltraShort")
        self.aravis_camera.set_exposure_time(90)  #140
        self.aravis_camera.set_gain(0)

        ##########NEW CODE FOR SHORT EXPOSURE##########
        #aravis_device = self.aravis_camera.get_device();
        #aravis_device.set_string_feature_value("ExposureTimeMode","UltraShort")
        #self.aravis_camera.set_exposure_time(7) #15 us
        #self.aravis_camera.set_gain(0)
        #self.aravis_camera.set_pixel_format (Aravis.PIXEL_FORMAT_MONO_8)
        #self.aravis_camera.set_trigger("Line1")
        #aravis_device.set_float_feature_value("LineDebouncerTime",5.0)

        ##########ORIGINAL CODE########################
        #self.aravis_camera.set_exposure_time(15) #1000000)#15 us
        #self.aravis_camera.set_gain(0)
        #self.aravis_camera.set_pixel_format (Aravis.PIXEL_FORMAT_MONO_8)
        #self.aravis_camera.set_trigger("Line1")

        self.payload = self.aravis_camera.get_payload()
        self.stream = self.aravis_camera.create_stream(None, None)

        ###

        #self.stream.set_property('packet-timeout',5000)
        #self.stream.set_property('frame-retention',250000)
        #self.stream.set_property('packet-request-ratio',0.1)
        #self.stream.set_property('socket-buffer',Aravis.GvStreamSocketBuffer.FIXED)
        #self.stream.set_property('socket-buffer-size',5000000)
        #self.stream.set_property('packet-resend',Aravis.GvStreamPacketResend.ALWAYS)

        ###

        if self.stream is None:
            print("Failed to construct stream")
            return
        self.aravis_camera.start_acquisition()
        for i in range(0, 16):
            self.stream.push_buffer(Aravis.Buffer.new_allocate(self.payload))

        #Print info about camera...
        print("Camera vendor : %s" % (self.aravis_camera.get_vendor_name()))
        print("Camera model  : %s" % (self.aravis_camera.get_model_name()))
        print("Camera id     : %s" % (self.aravis_camera.get_device_id()))
        print("Pixel format  : %s" %
              (self.aravis_camera.get_pixel_format_as_string()))

        print("Ready")
Ejemplo n.º 15
0
# Author: Emmanuel Pacaud <*****@*****.**>

#  If you have installed aravis in a non standard location, you may need
#   to make GI_TYPELIB_PATH point to the correct location. For example:
#
#   export GI_TYPELIB_PATH=$GI_TYPELIB_PATH:/opt/bin/lib/girepositry-1.0/
#
#  You may also have to give the path to libaravis.so, using LD_PRELOAD or
#  LD_LIBRARY_PATH.

import sys
import time

from gi.repository import Aravis

Aravis.enable_interface ("Fake")

try:
	if len(sys.argv) > 1:
		camera = Aravis.Camera.new (sys.argv[1])
	else:
		camera = Aravis.Camera.new (None)
except:
	print ("No camera found")
	exit ()

device = camera.get_device ()
genicam = device.get_genicam_xml ();

print genicam;
Ejemplo n.º 16
0
    async def _connect_internal(self, **kwargs):
        """Connect to a camera and upload basic binning and ROI parameters.
        :param kwargs:  recognizes the key uid with integer value, the serial number
                        If the key uid is absent, tries to attach to the first camera.
                        This is a subdictionary of 'cameras' in practise.
        """

        # print(self.name)
        # search for an optional uid key in the arguments
        try:
            uid = kwargs['uid']
        except:
            uid = None

        # reverse lookup of the uid in the list of known cameras
        cs = BlackflyCameraSystem(BlackflyCamera)
        slist = cs.list_available_cameras()

        if uid is None:
            # uid was not specified: grab the first device that is found
            # print("no uid provided, attaching to first camera")
            idx = 0
        else:
            # print("searching " + uid + " in " + str(slist) )
            idx = -1
            for id in slist:
                # remove the optional ip address of the id
                slistuid = id.split("@")[0]
                if slistuid == uid:
                    idx = slist.index(id)
            # not found
            if idx < 0:
                raise CameraConnectionError("SN " + uid + " not connected")

        cam = None
        try:
            if "@" in slist[idx]:
                # if the camera was not on local network use the address part
                cam = Aravis.Camera.new(slist[idx].split("@")[1])
            else:
                # otherwise the index is the same as the search order...
                cam = Aravis.Camera.new(Aravis.get_device_id(idx))
        except:
            raise CameraConnectionError(" not connected")

        # search for an optional gain key in the arguments
        # todo: one could interpret gain=0 here as to call set_gain_auto(ARV_AUTO_ON)
        try:
            gain = kwargs['gain']
            if gain > 0.0:
                # todo: it might make sense to squeeze this into the minimum
                # and maximum range of the camera's gain if outside that range.
                self.device.set_gain_auto(0)
                cam.set_gain(gain)
        except Exception as ex:
            # print("failed to set gain " + str(ex))
            pass

        # see arvenums.h for the list of pixel formats. This is MONO_16 here, always
        cam.set_pixel_format(0x01100007)

        # search for an optional x and y binning factor
        try:
            var = kwargs['binning']
            cam.set_binning(var[0], var[1])
        except Exception as ex:
            # print("failed to set binning " + str(ex))
            # horizontal and vertical binning set to 1
            cam.set_binning(1, 1)

        # scan the general list of genicam featured values
        # of the four native types
        for typp, arvLst in kwargs.items():
            if arvLst is not None:
                if typp == 'bool':
                    for genkey, genval in arvLst.items():
                        try:
                            cam.set_boolean(genkey, int(genval))
                        except:
                            # probably a typo in the yaml file... todo: log this
                            # print("failed for " + str(genkey)+str(genval))
                            pass
                elif typp == 'int':
                    for genkey, genval in arvLst.items():
                        try:
                            cam.set_integer(genkey, genval)
                        except:
                            # probably a typo in the yaml file... todo: log this
                            # print("failed for " + str(genkey)+str(genval))
                            pass
                elif typp == 'float':
                    for genkey, genval in arvLst.items():
                        try:
                            cam.set_float(genkey, genval)
                        except:
                            # probably a typo in the yaml file... todo: log this
                            # print("failed for " + str(genkey)+str(genval))
                            pass
                elif typp == 'string':
                    for genkey, genval in arvLst.items():
                        try:
                            cam.set_string(genkey, genval)
                        except:
                            # probably a typo in the yaml file... todo: log this
                            # print("failed for " + str(genkey)+str(genval))
                            pass

        dev = cam.get_device()

        # Take full frames by default (maximizing probability of LVM guide camera
        # to find guide stars in the field)
        roiBounds = [-1, -1]
        try:
            roiBounds[0] = dev.get_integer_feature_value("WidthMax")
            roiBounds[1] = dev.get_integer_feature_value("HeightMax")
            # print(" ROI " + str(roiBounds[0]) + " x " + str(roiBounds[1]) )
            cam.set_region(0, 0, roiBounds[0], roiBounds[1])
        except Exception as ex:
            # print("failed to set ROI " + str(ex))
            pass

        self.device = cam
        self.regionBounds = roiBounds
Ejemplo n.º 17
-1
def getcameraids():
    Aravis.update_device_list()
    n_cams = Aravis.get_n_devices()
    print("%d cameras found" % n_cams)
    ids = []
    for i in range(n_cams):
        dev_id = Aravis.get_device_id(i)
        print("Found: %s" % dev_id)
        ids.append(dev_id)
    return ids