Esempio n. 1
0
def captureImage():
    updateWeb()
    context = gp.Context()
    gp.Camera()
    C = gp.Camera()

    filename = 'Photoboothphoto_' + str(curTime()) + '.jpg'
    cap = C.capture(gp.GP_CAPTURE_IMAGE, context)
    print("Captured " + cap.folder + "/" + cap.name)
    file = C.file_get(cap.folder, cap.name, gp.GP_FILE_TYPE_NORMAL)
    gp.gp_file_save(file, filename)
    return filename
Esempio n. 2
0
def listMainSettings(args):
	camera = gp.Camera()
	camera.init()
	myConfigs = {
		'capturetarget': "",
		'iso': "",
		'f-number':"",
		'shutterspeed': "",
		'imagequality': "",
		'imagesize': ""
	}
	try:
		config = camera.get_config()
		for sections in config.get_children():
			if "settings" not in sections.get_name():
				continue
			print("\n#########{} ({})###########\n".format(sections.get_label(), sections.get_name()))
			for child in sections.get_children():
				if child.get_name() not in myConfigs:
					continue
				choicelist = []
				if child.get_type() == 5:
					for choice in child.get_choices():
						choicelist.append(choice)
				print("{} {} type:{} choices:{}".format(child.get_name(), child.get_value(), child.get_type(), choicelist))
				#else
				#for choice in 
	finally:
		camera.exit()
Esempio n. 3
0
    def discover(self):
        method = "gphoto2"
        discoverable = []
        context = gp.Context()
        try:
            for name, addr in context.camera_autodetect():
                now = str(datetime.datetime.now())
                c = gp.Context()
                camera = gp.Camera()
                camera.init(c)
                camera_summary = camera.get_summary(c)
                serial = ""
                for t in str(camera_summary).split("\n"):
                    if ("Serial Number:") in t:
                        serial = t.partition(":")[-1].strip()
                        # print(serial)
                        break
                camera.exit(c)
                discoverable.append({
                    "name": name,
                    "address": addr,
                    "uid": serial,
                    "discovery": method,
                    "lastseen": now,
                })

        except Exception as ex:
            print(ex)
        return discoverable
Esempio n. 4
0
def main():
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())
    camera = gp.Camera()
    camera.init()

    try:
        while True:
            print('Capturing image')
            file_path = camera.capture(gp.GP_CAPTURE_IMAGE)
            print(file_path.name)
            print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                     file_path.name))
            target = os.path.join('/tmp', file_path.name)
            print('Copying image to', target)
            camera_file = camera.file_get(file_path.folder, file_path.name,
                                          gp.GP_FILE_TYPE_NORMAL)
            camera_file.save(target)

            print("Rename")
            new_name = "/tmp/capt" + time.strftime("%Y%m%d%H%M%S.jpg",
                                                   time.gmtime())
            os.rename(target, new_name)
            subprocess.call(['xdg-open', new_name])
            time.sleep(4)

    except KeyboardInterrupt:
        camera.exit()
    return 0
def time_lapse():
    dateraw = datetime.datetime.now()
    datetimeformat = dateraw.strftime("%Y-%m-%d_%H:%M")
    print("RPi started taking photos for your timelapse at: " + datetimeformat)

    path, dirs, files = next(os.walk('/home/pi/Pictures/TimeLapse'))
    previous_photo_count = len(files)

    #Initializing camera
    camera = gp.Camera()
    camera.init()

    #system('rm /home/pi/Pictures/TimeLapse/*.jpg') #delete all photos in the Pictures folder before timelapse start

    for i in range(numphotos):
        print('Capturing image')
        file_path = camera.capture(gp.GP_CAPTURE_IMAGE)
        print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                 file_path.name))
        #target = os.path.join('/home/pi/Pictures/TimeLapse', 'frame%04d.jpg')
        target = ('/home/pi/Pictures/TimeLapse/frame{0:04d}.jpg'.format(
            (i + previous_photo_count)))
        print('Copying image to', target)
        camera_file = camera.file_get(file_path.folder, file_path.name,
                                      gp.GP_FILE_TYPE_NORMAL)
        #camera_file.save(target % i)
        camera_file.save(target)
        sleep(seconds_interval)
    print("Done taking photos.")
Esempio n. 6
0
    def open(self):
        context = gp.Context()
        camera = gp.Camera()
        camera.init(context)

        config = camera.get_config(context)

        # find and check the image format config item
        ok, image_format = gp.gp_widget_get_child_by_name(
            config, 'imageformat')
        if ok >= gp.GP_OK:
            value = gp.check_result(gp.gp_widget_get_value(image_format))
            if value == 'raw':
                raise RuntimeError('Cannot preview raw images!')

        # find and set the capture size class config item
        # this is required for some canon cameras and does not hurt for others
        ok, capture_size_class = gp.gp_widget_get_child_by_name(
            config, 'capturesizeclass')
        if ok >= gp.GP_OK:
            value = gp.check_result(
                gp.gp_widget_get_choice(capture_size_class, 2))
            gp.check_result(gp.gp_widget_set_value(capture_size_class, value))
            gp.check_result(gp.gp_camera_set_config(camera, config, context))

        self.context = context
        self.camera = camera
        self.config = config
Esempio n. 7
0
def test_focus_sweep():

    camera = gp.Camera()
    camera.init()

    config = camera.get_config()
    OK, bulb_child = gp.gp_widget_get_child_by_name(config, 'bulb')
    def detect_all_cameras(self):
        self.disconnect_all()

        with self._gp_lock:
            cameras_name_and_port = gp.check_result(gp.gp_camera_autodetect())

            # Search ports for camera port name
            port_info_list = gp.PortInfoList()
            port_info_list.load()

            for name, port in cameras_name_and_port:
                gp_camera = gp.Camera()
                idx = port_info_list.lookup_path(port)
                port_info = port_info_list[idx]
                gp_camera.set_port_info(port_info)

                try:
                    camera = GpCamera(name=name,
                                      port=port,
                                      gp_camera=gp_camera,
                                      lock=self.sync_lock)

                    with self._cameras_dict_lock:
                        self._cameras_dict[camera.id] = camera

                except Exception as e:
                    print('Detect all: {0}'.format(e))
Esempio n. 9
0
 def camera_find_by_serialnumber(self, serialnumber):
     logging.info(
         'camera_find_by_serialnumber: ++ sn = {}'.format(serialnumber))
     found = False
     ret = None
     try:
         cnt, cameras = gp.gp_camera_autodetect()
         for i in range(cnt):
             if len(cameras[i]) == 2:
                 addr = cameras[i][1]
                 port_info_list = gp.PortInfoList()
                 port_info_list.load()
                 idx = port_info_list.lookup_path(addr)
                 c = gp.Camera()
                 c.set_port_info(port_info_list[idx])
                 c.init()
                 config = c.get_config()
                 OK, sn = gp.gp_widget_get_child_by_name(
                     config, 'serialnumber')
                 if OK >= gp.GP_OK:
                     sn_text = sn.get_value()
                     if serialnumber == sn_text[-len(serialnumber):]:
                         found = True
                         ret = c
                 if not found:
                     c.exit()
             if found:
                 break
     except:
         pass
     logging.info('camera_find_by_serialnumber: -- ret={}'.format(ret))
     return ret
Esempio n. 10
0
def cameraInfo():
    camera = gp.Camera()
    camera.init()
    text = camera.get_summary()
    print('Summary')
    print(str(text))
    camera.exit()
Esempio n. 11
0
def main():
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    context = gp.Context()
    camera = gp.Camera()
    camera.init(context)
    files = list_files(camera, context)
    if not files:
        print('No files found')
        return 1
    print('File list')
    print('=========')
    for path in files[:10]:
        print(path)
    print('...')
    for path in files[-10:]:
        print(path)
    info = get_file_info(camera, context, files[-1])
    print
    print('File info')
    print('=========')
    print('image dimensions:', info.file.width, info.file.height)
    print('image type:', info.file.type)
    print('file mtime:', datetime.fromtimestamp(info.file.mtime).isoformat(' '))
    camera.exit(context)
    return 0
Esempio n. 12
0
    def __init__(self):
        Gtk.Window.__init__(self, title='Preview')
        box = Gtk.Box()
        self.files = FileManager()
        box.add(self.files)

        self.event_box = Gtk.EventBox()
        self.image = Gtk.Image()
        self.event_box.add(self.image)
        box.add(self.event_box)
        self.connect('delete-event', Gtk.main_quit)
        self.camera = gp.Camera()
        self.context = gp.Context()
        self.camera.init(self.context)

        configs = [
            (['settings', 'capture'], 1),
            (['imgsettings', 'iso'], '100')  # 1 = ISO 100
        ]

        set_config(self.camera, self.context, configs)
        time.sleep(1)
        GLib.idle_add(self.show_preview)
        self.event_box.connect('button_press_event', self.capture)

        self.add(box)
Esempio n. 13
0
 def start(self):
     self.camera = gp.Camera()
     self.camera.init()
     cfg = self.camera.get_config()
     cmode = cfg.get_child_by_name("capturemode")
     cmode.set_value(cmode.get_choice(0))  # should put in single shot mode
     self.is_started = True
Esempio n. 14
0
    def __init__(self, index):
        """
        Konstruktor der Klasse Camera.

        Beendet alle laufenden gphoto2 Prozesse.
        Nimmt einen Index entgegen und erstellt mit diesem aus der Liste der verfügbaren Kameras die ausgewählte Kamera.
        Weist die Kamera zum Schluss an, die aufgenommen Bilder auf der SD-Karte zu speichern.

        :param index: Index der ausgewählten Kamera.
        :rtype: int
        """

        self.index = index                                                                                              # Speichere den übergebenen Index
        Camera.kill_gphoto_process()                                                                                    # Beende alle laufenden gphoto2 Prozesse

        self.name, self.addr = Camera.available_cameras[index]                                                          # Entnehme den Namen und den Port der gewählten Kamera aus der Liste der verfügbaren Kameras
        self.camera = gp.Camera()                                                                                       # Erstelle ein neues Objekt vom Typ "gp.Camera"

        port_info_list = gp.PortInfoList()                                                                              # Lese die verfügbaren Ports (Usb) aus
        port_info_list.load()                                                                                           # Lade die Liste der Usb-Ports
        idx = port_info_list.lookup_path(self.addr)                                                                     # Lade den Pfad der Kamera aus der Liste
        self.camera.set_port_info(port_info_list[idx])                                                                  # Setze den Port des erstellen Kamera-Objektes auf den geladenen Pfad
        self.camera.init()                                                                                              # Initialisiere die Kamera

        self.set_capture_target()                                                                                       # Weise die Kamera an, Bilder auf der SD KArte zu speichern
        print("Kamera initialisiert")
Esempio n. 15
0
    def _setupCamera(self):

        self._ctxt = gp.Context()
        self._cap = gp.Camera()
        self._cap.init(self._ctxt)

        logging.info('Camera summary: %s',
                     str(self._cap.get_summary(self._ctxt)))

        # get configuration tree
        config = self._cap.get_config()

        # make sure camera format is not set to raw
        imageformat = config.get_child_by_name('imageformat')
        self._imageformat = imageformat.get_value()
        if 'raw' in self._imageformat.lower():
            imageformat.set_value('Large Fine JPEG')
        imageformatsd = config.get_child_by_name('imageformatsd')
        self._imageformatsd = imageformatsd.get_value()
        if 'raw' in self._imageformatsd.lower():
            imageformatsd.set_value('Large Fine JPEG')

        # make sure autopoweroff is disabled
        # this doesn't seem to work
        # autopoweroff = config.get_child_by_name('autopoweroff')
        # self._autopoweroff = autopoweroff.get_value()
        # logging.info('autopoweroff: {}'.format(self._autopoweroff))
        # if int(self._autopoweroff) > 0:
        #     autopoweroff.set_value('0')

        # apply configuration and print current config
        self._cap.set_config(config)
        self._printConfig(self._cap.get_config())
Esempio n. 16
0
    def start(self):
        right = True
        autodetected = gp.check_result(gp.gp_camera_autodetect())
        for i, cam in enumerate(autodetected):
            name, addr = cam
            if i == 0:
                right = get_bool(name + " connect in " + addr +
                                 " is Right cam ? (show left page) ")
            else:
                right = not self.camera_list[i - 1]["right"]
            # camera_list.append((name, addr))camera = gp.Camera()
            # search ports for camera port name
            camera = gp.Camera()
            port_info_list = gp.PortInfoList()
            port_info_list.load()
            idx = port_info_list.lookup_path(addr)
            camera.set_port_info(port_info_list[idx])
            camera.init()
            self.camera_list.append({
                "gp": camera,
                "name": name,
                "right": right
            })

        if not self.camera_list:
            print('No camera detected')
        else:
            canvas = np.zeros((512, 512, 3), np.uint8)
            while self.scanning:
                cv2.imshow('canvas', canvas)
                self.key_event(cv2.waitKey(100))
 def __init__(self):
     self.do_init = QtCore.QEvent.registerEventType()
     QtGui.QMainWindow.__init__(self)
     self.setWindowTitle("Camera config")
     self.setMinimumWidth(600)
     # quit shortcut
     quit_action = QtGui.QAction('Quit', self)
     quit_action.setShortcuts(['Ctrl+Q', 'Ctrl+W'])
     quit_action.triggered.connect(QtGui.qApp.closeAllWindows)
     self.addAction(quit_action)
     # main widget
     widget = QtGui.QWidget()
     widget.setLayout(QtGui.QGridLayout())
     widget.layout().setColumnStretch(0, 1)
     self.setCentralWidget(widget)
     # 'apply' button
     self.apply_button = QtGui.QPushButton('apply changes')
     self.apply_button.setEnabled(False)
     self.apply_button.clicked.connect(self.apply_changes)
     widget.layout().addWidget(self.apply_button, 1, 1)
     # 'cancel' button
     quit_button = QtGui.QPushButton('cancel')
     quit_button.clicked.connect(QtGui.qApp.closeAllWindows)
     widget.layout().addWidget(quit_button, 1, 2)
     # defer full initialisation (slow operation) until gui is visible
     self.context = gp.Context()
     self.camera = gp.Camera()
     QtGui.QApplication.postEvent(
         self, QtCore.QEvent(self.do_init), Qt.LowEventPriority - 1)
Esempio n. 18
0
def get_camera(serial, serial_to_address=None):
    if serial_to_address is None:
        serial_to_address = list_camera_serial_numbers()

    if len(serial_to_address) == 0:
        raise ValueError('No cameras!')
    if serial == '':
        print('Using first attached camera!')
        serial = serial_to_address.keys()[0]

    print('')
    print('===============')
    print('Selected camera:')
    print('===============')
    print('Serial Number: ' + serial)
    print('===============')
    print('')

    addr = serial_to_address[serial]
    camera = gp.Camera()
    port_info_list = gp.PortInfoList()
    port_info_list.load()
    idx = port_info_list.lookup_path(addr)
    camera.set_port_info(port_info_list[idx])
    camera.init()
    return camera
Esempio n. 19
0
def callCapImgFromTheta(reqName):

    camera = gp.Camera()
    camera.init()
    print ('[callCapTheta] Capture image')

    filePath = camera.capture(gp.GP_CAPTURE_IMAGE)
    tarPath = os.path.join('.', filePath.name)
    print ('[callCapTheta] Copying image to ', tarPath)

    cameraFile = camera.file_get(filePath.folder, filePath.name, gp.GP_FILE_TYPE_NORMAL)
    cameraFile.save(tarPath)

    camera.exit()

    #read image file
    with open(tarPath, 'rb') as f:
        img = f.read()

    binImg = base64.b64encode(img).decode('utf-8')

    content = {"id": location + ":" + reqName, "type": devType,
               "content": {"type": "Property", "value": binImg},
               "geometry": geometry}

    BODY = {reqName: content}

    BODY = json.dumps(BODY)

    print ("[callCapTheta] done!")

    if RMFLAG == 1:
        os.remove(tarPath)

    return BODY
Esempio n. 20
0
 def __init__(self):
     # Initialise the camera
     self.context = gp.Context()
     self.camera = gp.Camera()
     self.camera.init(self.context)
     # Check image format and determine the correct file suffix
     self.file_suffix = self.get_file_suffix()
Esempio n. 21
0
def list_camera_serial_numbers():
    camera_list = get_list_of_availale_cameras()
    if len(camera_list) == 0:
        return

    addresses = [camera_info[1] for camera_info in camera_list]
    camera_types = [camera_info[0] for camera_info in camera_list]

    serial_numbers = []
    serial_to_address = {}
    for i, addr in enumerate(addresses):
        camera = gp.Camera()
        port_info_list = gp.PortInfoList()
        port_info_list.load()
        idx = port_info_list.lookup_path(addr)
        camera.set_port_info(port_info_list[idx])
        camera.init()
        txt = str(camera.get_summary())
        serial = txt.split('Serial Number: ')[1].split('\n')[0]
        serial_numbers.append(serial)
        serial_to_address[serial_numbers[i]] = addresses[i]

    print('Attached Cameras:')
    print('================')
    for i in range(len(addresses)):
        print('Camera ' + str(i + 1))
        print('      Serial number: ' + serial_numbers[i])
        print('      Make and Model: ' + camera_types[i])
        print('      USB Address: ' + addresses[i])

    return serial_to_address
Esempio n. 22
0
def dingshi_paiZhao():
    global flag_start
    global mission_num
    global HeartBeat
    global photoNum
    logger.info('Capturing image')
    if os.path.exists("image/" + mission_num) is False:
        os.mkdir("image/" + mission_num)
    while flag_start == 1:
        try:
            camera = gphoto2.Camera()
            camera.init()
            file_path = camera.capture(gphoto2.GP_CAPTURE_IMAGE)
            logger.info('Camera file path: {0}/{1}'.format(
                file_path.folder, file_path.name))
            target = "image/" + mission_num + "/" + mission_num + "_" + str(
                photoNum) + ".jpg"
            logger.info('Copying image to ' + target)
            camera_file = camera.file_get(file_path.folder, file_path.name,
                                          gphoto2.GP_FILE_TYPE_NORMAL)
            camera_file.save(target)
            modify(target, HeartBeat['lat'], HeartBeat['lon'],
                   HeartBeat['alt'], HeartBeat['yaw'], HeartBeat['roll'],
                   HeartBeat['pitch'])
            photoNum = photoNum + 1
            time.sleep(5)
            camera.exit()
        except Exception as e:
            logger.info("paizhao:" + str(e))
            time.sleep(1)
Esempio n. 23
0
def delete_files():
    #print('Enter delete_files')
    folder = '/store_00010001/DCIM/100CANON'
    camera = gp.Camera()
    # camera.init()
    # gp.gp_camera_folder_delete_all(camera, folder)
    test = gp.check_result(gp.gp_camera_folder_delete_all(camera, folder))
Esempio n. 24
0
 def init_gcam(self, index, name, addr):
     self.camera = gp.Camera()
     port_info_list = gp.PortInfoList()
     port_info_list.load()
     idx = port_info_list.lookup_path(addr)
     self.camera.set_port_info(port_info_list[idx])
     self.camera.init()
Esempio n. 25
0
def main():
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.Camera()
    camera.init()
    files = list_files(camera)
    if not files:
        print('No files found')
        return 1
    print('File list')
    print('=========')
    for path in files[:10]:
        print(path)
    print('...')
    for path in files[-10:]:
        print(path)
    print()
    print('Exif data')
    print('=========')
    for path in files:
        if os.path.splitext(path)[1].lower() != '.jpg':
            continue
        exif = get_file_exif(camera, path)
        for key in ('EXIF DateTimeOriginal', 'EXIF LensModel',
                    'Image Copyright'):
            if key in exif:
                print(key, ':', exif[key])
        break
    print()
    camera.exit()
    return 0
def configured_camera():
    # Getting the camera
    context = gp.Context()
    cam = gp.Camera()
    cam.init(context)

    print(cam.get_summary(context))
    return cam
 def get_summary(self):
     context = gp.Context()
     camera = gp.Camera()
     camera.init(context)
     text = camera.get_summary(context)
     logging.debug(str(text))
     camera.exit(context)
     return str(text)
Esempio n. 28
0
 def init_camera(self):
     logging.info("Initializing camera")
     self.cam = gp.Camera()
     self.cam.init()
     self.config = self.cam.get_config()
     # Set capturetarget as SD card
     self.config.get_child_by_name("capturetarget").set_value("Memory card")
     self.cam.set_config(self.config)
Esempio n. 29
0
def init_camera(addr):
    camera = gp.Camera()
    # search ports for camera port name
    port_info_list = gp.PortInfoList()
    port_info_list.load()
    idx = port_info_list.lookup_path(addr)
    camera.set_port_info(port_info_list[idx])
    camera.init()
    return camera
Esempio n. 30
0
    def __init__(self):
        self.camera = gp.Camera()
        self.camera.init()
        abilities = self.camera.get_abilities()

        ##later can be converted to @property
        self.usb_vendor = abilities.usb_vendor
        self.usb_product = abilities.usb_product
        self.model = abilities.model