Exemplo n.º 1
0
def main():
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    print('Getting list of files')
    files = list_files(camera)
    if not files:
        print('No files found')
        return 1
    path = files[0]
    print('Copying %s to memory' % path)
    folder, name = os.path.split(path)
    camera_file = gp.check_result(
        gp.gp_camera_file_get(camera, folder, name, gp.GP_FILE_TYPE_NORMAL))
    ##    # read file data using 'slurp' and a buffer allocated in Python
    ##    info = gp.check_result(
    ##        gp.gp_camera_file_get_info(camera, folder, name))
    ##    file_data = bytearray(info.file.size)
    ##    count = gp.check_result(gp.gp_file_slurp(camera_file, file_data))
    ##    print(count, 'bytes read')
    # or read data using 'get_data_and_size' which allocates its own buffer
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    print('After deleting camera_file and file_data')
    del camera_file, file_data
    print(type(data), len(data))
    print(data[:10].tolist())
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
Exemplo n.º 2
0
 async def capture_preview(self):
     """ Capture preview image (doesn't engage curtain)
     """
     with (await self._lock):
         file = gp.check_result(gp.gp_camera_capture_preview(self._camera, self._context))
         data = gp.check_result(gp.gp_file_get_data_and_size(file))
         return bytes(data)
Exemplo n.º 3
0
def main():
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    print('Getting list of files')
    files = list_files(camera, context)
    if not files:
        print('No files found')
        return 1
    path = files[0]
    print('Copying %s to memory' % path)
    folder, name = os.path.split(path)
    camera_file = gp.check_result(gp.gp_camera_file_get(
        camera, folder, name, gp.GP_FILE_TYPE_NORMAL, context))
    data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    print(type(data), len(data))
    if six.PY2:
        print(map(ord, data[0:10]))
        image = Image.open(StringIO.StringIO(data))
    else:
        print(data[0:10])
        image = Image.open(io.BytesIO(data))
    image.show()
    print('After deleting camera_file')
    del camera_file
    print(type(data), len(data))
    if six.PY2:
        print(map(ord, data[0:10]))
    else:
        print(data[0:10])
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemplo n.º 4
0
    def capture(self, filename=None):
        """Capture a picture in a file. If no filename given a PIL image
        is returned.
        """
        camera_file = self._cam.capture_preview()
        file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
        image = Image.open(io.BytesIO(memoryview(file_data)))
        image = image.resize(pictures.resize_keep_aspect_ratio(image.size, self.resolution, 'outer'), Image.ANTIALIAS)
        image = image.crop(pictures.resize_by_croping(image.size, self.resolution))

        # Resize to the window rect (outer because rect already resized innner, see 'get_rect')
        rect = self.get_rect()
        size = pictures.resize_keep_aspect_ratio(image.size,  (rect.width, rect.height), 'outer')

        if self._preview_hflip:
            self._window.show_image(image.transpose(Image.FLIP_LEFT_RIGHT).resize(size))
        else:
            self._window.show_image(image.resize(size))

        if self._capture_hflip:
            image = image.transpose(Image.FLIP_LEFT_RIGHT)
        if filename:
            image.save(filename)
            return filename
        else:
            return image
Exemplo n.º 5
0
    def _get_preview_capture(self):
        """Capture a new preview image.
        """
        with timeit('Capturing new preview image'):
            camera_file = self._cam.capture_preview()
            file_data = gp.check_result(
                gp.gp_file_get_data_and_size(camera_file))
            image = Image.open(io.BytesIO(memoryview(file_data)))
            if self._preview_hflip:
                image = image.transpose(Image.FLIP_LEFT_RIGHT)
            if self._rotation:
                image = image.rotate(self._rotation)

            image = image.resize(
                sizing.new_size_keep_aspect_ratio(image.size, self.resolution,
                                                  'outer'))
            image = image.crop(
                sizing.new_size_by_croping(image.size, self.resolution))

        # Resize to the window rect (outer because rect already resized innner, see 'get_rect')
        rect = self.get_rect()
        return image.resize(
            sizing.new_size_keep_aspect_ratio(image.size,
                                              (rect.width, rect.height),
                                              'outer'))
Exemplo n.º 6
0
    def __take_preview_pic(self):
        print 'camera.__take_preview_pic'
        image = QtGui.QImage()
        if not self.use_real_camera:
            image.load('./data/preview.jpg')
        else:
            camera_file = gp.check_result(gp.gp_camera_capture_preview(self.__camera, self.__context))
            file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
            image_data = io.BytesIO(file_data)
            self.__pub_image(image_data.getvalue())
            image.loadFromData(image_data.getvalue())

        if self.__count_down_start!=None and self.draw_countdown:
            p = QtGui.QPainter(image)
            p.setPen(Camera.countdown_pen)
            size = 180
            p.setFont(QtGui.QFont("Arial",size))
            p.drawText((image.width()+size)/2,
                       (image.height()+size)/2,
                       '%i'%(self.__count_down_n))
            p.end()
        image = image.scaledToHeight(self.__preview_height,
                                    transformMode=QtCore.Qt.SmoothTransformation)

        self.new_preview_image.emit(image.transformed(self.__preview_transform))
Exemplo n.º 7
0
def initializecamera():
    global camera #相机
    global back_path #背景图路径
    global img_back1 #背景图
    global image_width #相机预览图的宽
    global image_height #相机预览图的高
    global scale_factor #获取图像缩小的倍数
    global screen_width, screen_height

    Killgphoto2Process() #先停止gphoto2 运行线程

    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    camera_file = gp.check_result(gp.gp_camera_capture_preview(camera))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    image = Image.open(io.BytesIO(file_data))
    frame = np.array(image)
    image_height, image_width = frame.shape[:2]     # 获得相机预览图片大小
    print('相机预览画面 宽/高=', image_width,'/', image_height)
    img_back1 = cv.imread(back_path)    # 绿幕背景图片
    img_back1 = cv.resize(img_back1,(image_width,image_height))  # 改变背景图片分辨率
    if image_width > 900:
        scale_factor = 0.5
    else:
        scale_factor = 1
Exemplo n.º 8
0
def main():
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    print('Getting list of files')
    files = list_files(camera, context)
    if not files:
        print('No files found')
        return 1
    path = files[0]
    print('Copying %s to memory' % path)
    folder, name = os.path.split(path)
    camera_file = gp.check_result(gp.gp_camera_file_get(
        camera, folder, name, gp.GP_FILE_TYPE_NORMAL, context))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    print('After deleting camera_file and file_data')
    del camera_file, file_data
    print(type(data), len(data))
    print(data[:10].tolist())
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemplo n.º 9
0
def take_picture(camera: gp.camera,
                 rotation_pos: int, declination_pos: int,
                 queue: beanstalk.Connection) -> str:
    """take a picture and save it to the USB drive
    or the google drive, if specified"""

    # take the picture
    file_path = gp.check_result(gp.gp_camera_capture(
        camera, gp.GP_CAPTURE_IMAGE))
    file_name = 'P{dec:02d}{rot:02d}_'.\
                    format(dec=declination_pos, rot=rotation_pos) + file_path.name

    # read the photo from the camera
    camera_file = gp.check_result(gp.gp_camera_file_get(camera,
                                                        file_path.folder,
                                                        file_path.name,
                                                        gp.GP_FILE_TYPE_NORMAL))

    # if a google drive isn't specified, write to the local USB drive
    # read the image from the camera into memory
    # and upload it
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))

    # okay, upload to the Google drive via a thread...
    byte_stream = io.BytesIO(file_data)
    camera_bytes = byte_stream.read(-1)
    job = {'task': 'photo',
           'filename': file_name,
           'data': base64.encodebytes(camera_bytes).decode('ascii')}
    # now send the photo to the Google Drive process
    queue.use(google_drive.GDRIVE_QUEUE)
    job_str = json.dumps(job)
    print("photo job size is {0} bytes".format(len(job_str)))
    queue.put(job_str)
    return file_name
Exemplo n.º 10
0
    def update(self):
        # keep looping infinitely until the thread is stopped
        while True:
            camera_file = gp.check_result(
                gp.gp_camera_capture_preview(self.camera))
            file_data = gp.check_result(
                gp.gp_file_get_data_and_size(camera_file))
            self.frame = memoryview(file_data)

            # if the capture indicator is set, grab full size pic
            if (self.shotRequested):
                file_path = self.camera.capture(gp.GP_CAPTURE_IMAGE)
                print('Camera file path: {0}/{1}'.format(
                    file_path.folder, file_path.name))
                print('Copying image to', '/tmp/still.jpg')
                camera_file = self.camera.file_get(file_path.folder,
                                                   file_path.name,
                                                   gp.GP_FILE_TYPE_NORMAL)
                camera_file.save('/tmp/still.jpg')
                #self.shot = memoryview(camera_file)
                self.shotRequested = False

            # if the thread indicator variable is set, stop the thread
            # and resource camera resources
            if self.stopped:
                self.camera.exit()
                return
Exemplo n.º 11
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.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    print('Getting list of files')
    files = list_files(camera)
    if not files:
        print('No files found')
        return 1
    path = files[0]
    print('Copying %s to memory' % path)
    folder, name = os.path.split(path)
    camera_file = gp.check_result(gp.gp_camera_file_get(
        camera, folder, name, gp.GP_FILE_TYPE_NORMAL))
##    # read file data using 'slurp' and a buffer allocated in Python
##    info = gp.check_result(
##        gp.gp_camera_file_get_info(camera, folder, name))
##    file_data = bytearray(info.file.size)
##    count = gp.check_result(gp.gp_file_slurp(camera_file, file_data))
##    print(count, 'bytes read')
    # or read data using 'get_data_and_size' which allocates its own buffer
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    print('After deleting camera_file and file_data')
    del camera_file, file_data
    print(type(data), len(data))
    print(data[:10].tolist())
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
Exemplo n.º 12
0
    def get_exif_extract_from_jpeg(self, folder: str,
                                   file_name: str) -> bytearray:
        """
        Extract strictly the app1 (exif) section of a jpeg.

        Uses libgphoto2 to extract the exif header.

        Assumes jpeg on camera is straight from the camera, i.e. not
        modified by an exif altering program off the camera.

        :param folder: directory on the camera where the jpeg is stored
        :param file_name: name of the jpeg
        :return: first section of jpeg such that it can be read by
         exiv2 or similar

        """

        camera_file = self._get_file(folder, file_name, None,
                                     gp.GP_FILE_TYPE_EXIF)

        try:
            exif_data = gp.check_result(
                gp.gp_file_get_data_and_size(camera_file))
        except gp.GPhoto2Error as ex:
            logging.error(
                "Error getting exif info for %s from camera %s: %s",
                os.path.join(folder, file_name),
                self.display_name,
                gphoto2_named_error(ex.code),
            )
            raise CameraProblemEx(code=CameraErrorCode.read, gp_exception=ex)
        return bytearray(exif_data)
Exemplo n.º 13
0
    def capture(self):
        with open_camera() as (camera, context):
            # Capture picture
            camera_path = self._trigger(camera, context)
            folder = camera_path.folder
            name = camera_path.name

            # Get picture file
            error, camera_file = gp.gp_camera_file_get(camera, folder, name,
                                                       gp.GP_FILE_TYPE_NORMAL,
                                                       context)

            file_data = gp.check_result(
                gp.gp_file_get_data_and_size(camera_file))

            picture = Image.open(cStringIO.StringIO(file_data))
            exif_dict = piexif.load(picture.info["exif"])
            cropped = crop_to_square(picture)

            s, _ = cropped.size
            exif_dict["Exif"][piexif.ExifIFD.PixelXDimension] = s
            exif_bytes = piexif.dump(exif_dict)

            buf = cStringIO.StringIO()
            cropped.save(buf, "JPEG", exif=exif_bytes)
            cropped = buf.getvalue()
            buf.close()

            return cropped
Exemplo n.º 14
0
        def capture():
            path = gp.check_result(gp.gp_camera_capture(self._camera, gp.GP_CAPTURE_IMAGE, self._context))

            file = gp.check_result(gp.gp_camera_file_get(
                self._camera, path.folder, path.name,
                gp.GP_FILE_TYPE_NORMAL, self._context))

            data = gp.check_result(gp.gp_file_get_data_and_size(file))
            return bytes(data)
Exemplo n.º 15
0
 def take_preview_image(self):
     # self.log.debug("taking preview photo via GPhoto2")
     camera_file = gp.check_result(gp.gp_camera_capture_preview(
         self.camera))
     file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
     # decode image
     img = cv2.imdecode(
         np.fromstring(io.BytesIO(file_data).read(), np.uint8), 1)
     return resize(img, width=self.preview_width)
Exemplo n.º 16
0
def captureImage(camera):
    if camera == None:
        print("Invalid camera instance")
        return None
    camera_file = gp.check_result(gp.gp_camera_capture_preview(camera))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    data = memoryview(file_data)
    image = Image.open(io.BytesIO(file_data))
    image = np.array(image)
    return image
Exemplo n.º 17
0
 def capture_next_preview_as_np_array(self):
     try:
         preview_file = self.camera.capture_preview()
         preview_path = gp.check_result(
             gp.gp_file_get_data_and_size(preview_file))
         img = self._convert_camera_to_np_array(preview_path)
         logging.debug(f"camera preview data: {img} ")
         return cv2.imdecode(img, cv2.IMREAD_COLOR)
     except Exception as ex:
         logging.error(
             f"Error while capturing the preview: {type(ex).__name__}",
             exc_info=ex)
Exemplo n.º 18
0
def main():
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.ERROR)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    # required configuration will depend on camera type!
    print('Checking camera config')
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera))
    # find the image format config item
    OK, image_format = gp.gp_widget_get_child_by_name(config, 'imageformat')
    if OK >= gp.GP_OK:
        # get current setting
        value = gp.check_result(gp.gp_widget_get_value(image_format))
        # make sure it's not raw
        if 'raw' in value.lower():
            print('Cannot preview raw images')
            return 1
    # find the capture size class config item
    # need to set this on my Canon 350d to get preview to work at all
    OK, capture_size_class = gp.gp_widget_get_child_by_name(
        config, 'capturesizeclass')
    if OK >= gp.GP_OK:
        # set value
        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))
        # set config
        gp.check_result(gp.gp_camera_set_config(camera, config))
    # capture preview image (not saved to camera memory card)
    print('Capturing preview image')

    for x in xrange(1,100):
        millis = int(round(time.time() * 1000))

        camera_file = gp.check_result(gp.gp_camera_capture_preview(camera))

        print("capture %d %s\n" % (int(round(time.time() * 1000)) - millis, camera_file))

        file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))

        print("download %d\n" % (int(round(time.time() * 1000)) - millis))

        data = memoryview(file_data)

    # display image
    #image = Image.open(io.BytesIO(file_data))
    #image.show()
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
Exemplo n.º 19
0
def wait_for_frame_gphoto2(prev_frame, wname, cam, size):
    '''
    onionskin prev_frame while displaying 
    gphoto2 version
    '''
    key = 1
    while key not in [13, 27]:
        key = cv2.waitKey(7)
        camera_file = gp.check_result(gp.gp_camera_capture_preview(cam))
        file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
        im = np.array(Image.open(io.BytesIO(file_data)))[:, :, ::-1]
        # display the current frame with the prev_frame onionskinned
        im2 = cv2.addWeighted(prev_frame, 0.5, im, 0.5, 0)
        cv2.imshow(wname, cv2.resize(im2, size))
    exp = 5
    imret = im
    return imret, key
Exemplo n.º 20
0
def saveFrames_gphoto2(wname, cam, direc):
    '''
    stupid thing trying to mimic FrameByFrame
    Save individual frames with Return, stop frame capture with Esc
    gphoto2 version--supports capture from a DSLR
    '''
    camera_file = gp.check_result(gp.gp_camera_capture_preview(cam))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    im0 = np.array(Image.open(io.BytesIO(file_data)))

    size = (im0.shape[1], im0.shape[0])
    key = 1
    counter = 0
    while key != 27:
        im0, key = wait_for_frame_gphoto2(im0, wname, cam, size)
        cv2.imwrite(os.path.join(direc, str(counter).zfill(4) + '.jpg'), im0)
        counter += 1
Exemplo n.º 21
0
def take_a_pic():
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    # required configuration will depend on camera type!
    print('Checking camera config')
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera))
    # find the image format config item
    OK, image_format = gp.gp_widget_get_child_by_name(config, 'imageformat')
    if OK >= gp.GP_OK:
        # get current setting
        value = gp.check_result(gp.gp_widget_get_value(image_format))
        # make sure it's not raw
        if 'raw' in value.lower():
            print('Cannot preview raw images')
            return 1
            # find the capture size class config item
            # need to set this on my Canon 350d to get preview to work at all
            OK, capture_size_class = gp.gp_widget_get_child_by_name(
                config, 'capturesizeclass')
            if OK >= gp.GP_OK:
                # set value
                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))
                # set config
                gp.check_result(gp.gp_camera_set_config(camera, config))
                # capture preview image (not saved to camera memory card)
                print('Capturing preview image')
                camera_file = gp.check_result(
                    gp.gp_camera_capture_preview(camera))
                file_data = gp.check_result(
                    gp.gp_file_get_data_and_size(camera_file))
                # display image
                data = memoryview(file_data)
                print(type(data), len(data))
                print(data[:10].tolist())
                image = Image.open(io.BytesIO(file_data))
                image.show()
                gp.check_result(gp.gp_camera_exit(camera))
                return image
Exemplo n.º 22
0
    def get_preview(self):
        if self.use_cached is False:
            try:
                camera_file = gp.check_result(
                    gp.gp_camera_capture_preview(self.camera))
            except gp.GPhoto2Error:
                camera_file = self.file_cache
        else:
            camera_file = self.file_cache

        if camera_file is None:
            camera_file = gp.check_result(
                gp.gp_camera_capture_preview(self.camera))

        self.file_cache = camera_file
        file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))

        return file_data
 def show_preview(self):
     
     if(self.parent.canonCemara.isconnec):
         if self.isplay:
             if not self.ispreview :
                 self.ispreview=True
                 try:
                     camera_file = gp.check_result(gp.gp_camera_capture_preview(self.parent.canonCemara.camera))
                     file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
                     image = Image.open(io.BytesIO(file_data))
                     self.pixmap=self.PILimageToQImage(image)
                     self.imageLabel.setPixmap(self.pixmap)
                 except Exception as e:
                     print("Frame Read error")
                 self.ispreview=False
         elif self.iscapture_image:
             self.iscapture_image=False
             self.pixmap=self.PILimageToQImage(self.capture_image)
             self.imageLabel.setPixmap(self.pixmap)
Exemplo n.º 24
0
def main():
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    context = gp.gp_context_new()
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera, context))
    # required configuration will depend on camera type!
    print('Checking camera config')
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera, context))
    # find the image format config item
    OK, image_format = gp.gp_widget_get_child_by_name(config, 'imageformat')
    if OK >= gp.GP_OK:
        # get current setting
        value = gp.check_result(gp.gp_widget_get_value(image_format))
        # make sure it's not raw
        if 'raw' in value.lower():
            print('Cannot preview raw images')
            return 1
    # find the capture size class config item
    # need to set this on my Canon 350d to get preview to work at all
    OK, capture_size_class = gp.gp_widget_get_child_by_name(
        config, 'capturesizeclass')
    if OK >= gp.GP_OK:
        # set value
        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))
        # set config
        gp.check_result(gp.gp_camera_set_config(camera, config, context))
    # capture preview image (not saved to camera memory card)
    print('Capturing preview image')
    camera_file = gp.check_result(gp.gp_camera_capture_preview(camera, context))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    # display image
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemplo n.º 25
0
def preview():
    OK, capture_size_class = gp.gp_widget_get_child_by_name(
        config, 'capturesizeclass')
    if OK >= gp.GP_OK:
        # set value
        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))
        # set config
        gp.check_result(gp.gp_camera_set_config(camera, config))
    # capture preview image (not saved to camera memory card)
    print('Capturing preview image')
    camera_file = gp.check_result(gp.gp_camera_capture_preview(camera))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    # display image
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    return 0
Exemplo n.º 26
0
    def get_thumbnail(
        self,
        dir_name: str,
        file_name: str,
        ignore_embedded_thumbnail=False,
        cache_full_filename: Optional[str] = None,
    ) -> Optional[bytes]:
        """
        :param dir_name: directory on the camera
        :param file_name: the photo or video
        :param ignore_embedded_thumbnail: if True, do not retrieve the
        embedded thumbnail
        :param cache_full_filename: full path including filename where the
        thumbnail will be saved. If none, will not save it.
        :return: thumbnail in bytes format, which will be full
        resolution if the embedded thumbnail is not selected
        """

        if self.can_fetch_thumbnails and not ignore_embedded_thumbnail:
            get_file_type = gp.GP_FILE_TYPE_PREVIEW
        else:
            get_file_type = gp.GP_FILE_TYPE_NORMAL

        camera_file = self._get_file(dir_name, file_name, cache_full_filename,
                                     get_file_type)

        try:
            thumbnail_data = gp.check_result(
                gp.gp_file_get_data_and_size(camera_file))
        except gp.GPhoto2Error as ex:
            logging.error(
                "Error getting image %s from camera %s: %s",
                os.path.join(dir_name, file_name),
                self.display_name,
                gphoto2_named_error(ex.code),
            )
            raise CameraProblemEx(code=CameraErrorCode.read, gp_exception=ex)

        if thumbnail_data:
            data = memoryview(thumbnail_data)
            return data.tobytes()
Exemplo n.º 27
0
    def slurpd(self, device, apply_state=True):

        if apply_state:
            self.apply_state(device)

        try:
            logger.info(device)

            context = gp.gp_context_new()
            camera = gp.Camera()

            cameras = gp.PortInfoList()
            cameras.load()
            camera_address = cameras.lookup_path(device['address'])
            camera.set_port_info(cameras[camera_address])
            gp.check_result(gp.gp_camera_init(camera, context))

            captured = gp.check_result(
                gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context))

            captured_file = gp.check_result(
                gp.gp_camera_file_get(camera, captured.folder, captured.name,
                                      gp.GP_FILE_TYPE_NORMAL, context))

            captured_file_data = gp.check_result(
                gp.gp_file_get_data_and_size(captured_file))
            container = io.BytesIO(memoryview(captured_file_data))
            container.seek(0)
            contents = container.read()

            gp.check_result(gp.gp_camera_exit(camera, context))

        except Exception as ex:
            logger.warn(ex)
            self.broadcast(channel=self.channels['exception'],
                           message=str(ex),
                           subs=[{
                               "function": sys._getframe().f_code.co_name
                           }])

        return contents
Exemplo n.º 28
0
 def run(self):
   while not self.doStop:
     if self.picture is None:
       try:
         if self.doStop:
           self.idle=True
           return
         self.idle=False
         camera_file = gp.check_result(gp.gp_camera_capture_preview(self.camera, self.context))
         if self.doStop:
           self.idle=True
           return
         file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
         self.picture=file_data
       except:
         self.idle=True
         self.cameraError=True
         return
       self.idle=True
     time.sleep(0.005)
   self.idle=True
Exemplo n.º 29
0
    def get_THM_file(self, full_THM_name: str) -> Optional[bytes]:
        """
        Get THM thumbnail from camera

        :param full_THM_name: path and file name of the THM file
        :return: THM in raw bytes
        """
        dir_name, file_name = os.path.split(full_THM_name)
        camera_file = self._get_file(dir_name, file_name)
        try:
            thumbnail_data = gp.check_result(
                gp.gp_file_get_data_and_size(camera_file))
        except gp.GPhoto2Error as ex:
            logging.error('Error getting THM file %s from camera %s: %s',
                          os.path.join(dir_name, file_name), self.display_name,
                          gphoto2_named_error(ex.code))
            raise CameraProblemEx(code=CameraErrorCode.read, gp_exception=ex)

        if thumbnail_data:
            data = memoryview(thumbnail_data)
            return data.tobytes()
Exemplo n.º 30
0
def preview_image():
    callback_obj = gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    # required configuration will depend on camera type!
    print('Checking camera config')
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera))
    # find the image format config item
    # camera dependent - 'imageformat' is 'imagequality' on some
    OK, image_format = gp.gp_widget_get_child_by_name(config, 'imageformat')
    if OK >= gp.GP_OK:
        # get current setting
        value = gp.check_result(gp.gp_widget_get_value(image_format))
        # make sure it's not raw
        if 'raw' in value.lower():
            print('Cannot preview raw images')
            # return 1
    # find the capture size class config item
    # need to set this on my Canon 350d to get preview to work at all
    OK, capture_size_class = gp.gp_widget_get_child_by_name(
        config, 'capturesizeclass')
    if OK >= gp.GP_OK:
        # set value
        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))
        # set config
        gp.check_result(gp.gp_camera_set_config(camera, config))
    # capture preview image (not saved to camera memory card)
    print('Capturing preview image')
    camera_file = gp.check_result(gp.gp_camera_capture_preview(camera))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    # display image

    data = memoryview(file_data)
    image = cv2.imdecode(np.asarray(bytearray(data), dtype=np.uint8), 3)
    cv2.imshow("preview",image)
    cv2.waitKey()
    # image.show()
    gp.check_result(gp.gp_camera_exit(camera))
Exemplo n.º 31
0
 def run_preview(self):
     logging.info('run_preview: ++')
     rc = redis.Redis()
     while not self.quitEvent.is_set():
         x = rc.get('camera.TP')
         if bool(x):
             x = x.decode('utf-8')
             camera = self.camera_find_by_serialnumber(x)
             if camera is not None:
                 # self.get_ev(camera)
                 # frame=0
                 while not self.quitEvent.is_set():
                     try:
                         # if bool(self.new_ev):
                         #     err, ep = gp.gp_camera_get_single_config(camera, 'exposurecompensation')
                         #     if err >= gp.GP_OK:
                         #         v = ep.get_value()
                         #         ep.set_value(self.new_ev)
                         #         err = gp.gp_camera_set_single_config(camera, 'exposurecompensation', ep)
                         #         if err >= gp.GP_OK:
                         #             self.ev = self.new_ev
                         #             self.new_ev = None
                         camera_file = camera.capture_preview()
                         # frame += 1
                         # logging.info('frame: {}'.format(frame))
                         err, buf = gp.gp_file_get_data_and_size(
                             camera_file)
                         if err >= gp.GP_OK:
                             image = Image.open(io.BytesIO(buf))
                             image = image.rotate(180)
                             if self.cb is not None:
                                 self.cb(image)
                     except:
                         pass
                 camera.exit()
             else:
                 time.sleep(3)
     rc.close()
     logging.info('run_preview: --')
     pass
Exemplo n.º 32
0
    def capture(self, req):
        rospy.loginfo('Capturing panorama')
        if not self.single_capture():
            rospy.logerr('Could not trigger Richo Theta, retrying in 1s')
            rospy.sleep(1)
            while not self.single_capture():
                rospy.logerr(
                    'Could not trigger Richo Theta, resetting the usb driver. Is the camera switched on and set to still image capture mode?'
                )
                reset_usb_driver()
                self.init_camera()
                rospy.sleep(2)

        # Construct image
        file_data = gp.check_result(
            gp.gp_file_get_data_and_size(self.camera_file))
        img = Img.open(io.BytesIO(file_data))
        rospy.loginfo('Panorama captured!')

        image = Image(height=img.height,
                      width=img.width,
                      encoding="rgb8",
                      is_bigendian=False,
                      step=img.width * 3,
                      data=img.tobytes())
        image.header.stamp = self.stamp
        image.header.frame_id = 'map'  #TODO maybe add something sensible here

        self.pub_image.publish(image)
        rospy.loginfo('Panorama published!')

        # Avoid running out of space. Update: No need: Device holds approx 4,800 photos
        #try:
        #    self.camera.file_delete(self.file_path.folder, self.file_path.name)
        #except:
        #    rospy.logwarn('Delete photo on the Ricoh Theta failed. Camera may eventually run out of storage.')
        return TriggerResponse(success=True,
                               message=self.file_path.folder + '/' +
                               self.file_path.name)
Exemplo n.º 33
0
 def run(self):
     while not self.doStop:
         if self.picture is None:
             try:
                 if self.doStop:
                     self.idle = True
                     return
                 self.idle = False
                 camera_file = gp.check_result(
                     gp.gp_camera_capture_preview(self.camera,
                                                  self.context))
                 if self.doStop:
                     self.idle = True
                     return
                 file_data = gp.check_result(
                     gp.gp_file_get_data_and_size(camera_file))
                 self.picture = file_data
             except:
                 self.idle = True
                 self.cameraError = True
                 return
             self.idle = True
         time.sleep(0.005)
     self.idle = True
Exemplo n.º 34
0
    def slurpd(self, device):
        contents = b""
        try:
            context = gp.gp_context_new()
            camera = gp.Camera()

            cameras = gp.PortInfoList()
            cameras.load()
            camera_address = cameras.lookup_path(device["address"])
            camera.set_port_info(cameras[camera_address])
            gp.check_result(gp.gp_camera_init(camera, context))

            captured = gp.check_result(
                gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context))

            captured_file = gp.check_result(
                gp.gp_camera_file_get(
                    camera,
                    captured.folder,
                    captured.name,
                    gp.GP_FILE_TYPE_NORMAL,
                    context,
                ))

            captured_file_data = gp.check_result(
                gp.gp_file_get_data_and_size(captured_file))
            container = io.BytesIO(memoryview(captured_file_data))
            container.seek(0)
            contents = container.read()

            gp.check_result(gp.gp_camera_exit(camera, context))

        except Exception as ex:
            print(ex)

        return contents
Exemplo n.º 35
0
	def capture(self):

		while True:
			try:
				for i in range(0,20):
					try:
						camera_file = gp.check_result(gp.gp_camera_capture_preview(self.camera, self.context))
						break
					except gp.GPhoto2Error as ex:
						if i < 19:
							continue
					raise
						
				file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
	
				pil_image = Image.open(io.BytesIO(file_data))
				#pil_image.save("testimg2_" + str(i) + ".tif")
				im = np.array(pil_image)
				im = apply_gamma(im, 2.2)
				if self.fpshackiso > 0:
					self.set_config_value_checked('iso', 1600)
					self.set_config_value_checked('iso', 100)
					self.fpshackiso -= 1

				return im, None
	
			except KeyboardInterrupt:
				break
			except gp.GPhoto2Error as ex:
				print "Unexpected error: " + sys.exc_info().__str__()
				print "code:", ex.code
				stacktraces()
				time.sleep(1)
				if ex.code == -7 or ex.code == -1:
					gp.gp_camera_exit(self.camera, self.context)
					self.prepare()
Exemplo n.º 36
0
def main():
    logging.basicConfig( format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    print('Establishing communication with the camera (wait few seconds)')
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    # required configuration will depend on camera type!
    config = gp.check_result(gp.gp_camera_get_config(camera))
    print('Camera ready')

    # TODO  get the list of 'gp_abilities_list_get_abilities' or something like that ? 
    #  --> find out how to set image format
    #  --> also use it to set shutter and ISO
    def my_set(name, value):
        OK, widget = gp.gp_widget_get_child_by_name(config, name)
        if OK >= gp.GP_OK:
            widget_type = gp.check_result(gp.gp_widget_get_type(widget))
            gp.check_result(gp.gp_widget_set_value(widget, value))
            gp.check_result(gp.gp_camera_set_config(camera, config))
        else:
            print("Error setting value %s for %s using widget %s" % (value, name, widget))
    #my_set(name='imageformat', value='Large Fine JPEG')
    my_set(name='imageformat', value='RAW')
    my_set(name='shutterspeed', value='{}'.format(shutterspeed))
    my_set(name='iso', value='{}'.format(iso))

    # find the image format config item
    OK, image_format = gp.gp_widget_get_child_by_name(config, 'imageformat')
    if OK >= gp.GP_OK:
        imgformat = gp.check_result(gp.gp_widget_get_value(image_format))

    # find the capture size class config item
    # need to set this on my Canon 350d to get preview to work at all
    OK, capture_size_class = gp.gp_widget_get_child_by_name(config, 'capturesizeclass')
    if OK >= gp.GP_OK:
        # set value
        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))
        # set config
        gp.check_result(gp.gp_camera_set_config(camera, config))


    # capture preview image (not saved to camera memory card)
    print('Capturing preview image')
    camera_file = gp.check_result(gp.gp_camera_capture_preview(camera))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    print('01----------', type(file_data),file_data)

    # display image
    data = memoryview(file_data)
    print('02----------', type(data), data)
    print('    ', len(data))
    print(data[:10].tolist())
    if 'raw' in imgformat.lower():
        #rawimage = open(io.BytesIO(file_data))
        ## FIXME raw format would be more accurate than JPEG, but  AttributeError: '_io.BytesIO' object has no attribute 'encode'
        #xx from rawkit import raw
        #xx raw_image_process = raw.Raw(io.BytesIO(file_data))

        #import rawpy
        #raw = rawpy.imread(bytesio)
        #rgb = raw.postprocess()

        #bytesio = io.BytesIO(file_data)
        #print('bytesio', bytesio)
        raw_file_name = 'image_logs/output_debayered_{}s_ISO{}_{}.cr2'.format(shutterspeed.replace('/','div'), iso, comment)
        gp.gp_file_save(camera_file, raw_file_name)

        # Note that - if Canon cameras are used - the dependency on rawkit can be replaced with a dedicated parser
        #https://codereview.stackexchange.com/questions/75374/cr2-raw-image-file-parser-in-python-3

        from rawkit.raw import Raw
        from rawkit.options import interpolation
        raw_image = Raw(filename=raw_file_name)
                # 'bayer_data', 'close', 'color', 'color_description', 'color_filter_array', 'data', 
                # 'image_unpacked', 'libraw', 'metadata', 'options', 'process', 'raw_image', 'save', 
                # 'save_thumb', 'thumb_unpacked', 'thumbnail_to_buffer', 'to_buffer', 'unpack', 'unpack_thumb'
        #raw_image.options.interpolation = interpolation.linear # or "amaze", see https://rawkit.readthedocs.io/en/latest/api/rawkit.html
        raw_image.options.interpolation = interpolation.amaze # or "amaze", see https://rawkit.readthedocs.io/en/latest/api/rawkit.html

        raw_image.save("output-test.ppm") ## FIXME - saved ppm image has auto-normalized brightness, why?

        raw_image_process = raw_image.process()
        if raw_image_process is raw_image: print("they are identical")


        ## FIXME - 
        npimage = np.array(raw_image.raw_image(include_margin=False)) # returns: 2D np. array
        #print('bayer_data', raw_image.bayer_data()) #  ? 
        #print('as_array', raw_image.as_array()) # does not exist, although documented??
        #print(type(raw_image.to_buffer())) # Convert the image to an RGB buffer. Return type:	bytearray

        #npimage = np.array(flat_list).reshape(4)
        print(npimage) ## gives 1-d array of values
        print(npimage.shape) ## gives 1-d array of values

        plt.imshow(npimage)
        plt.hist(npimage.flatten(), 4096)
        #plt.plot([200,500], [300,-100], lw=5, c='r')
        #plt.show()

        ## Save the raw pixels
        try: import cPickle as pickle
        except: import pickle

        print('retrieved image as numpy array with dimensions:', npimage.shape)

        #scipy.ndimage.
        print('', )
        print('', )

        print(npimage.shape)
    else:
        image = Image.open(io.BytesIO(file_data))
        npimage = np.array(image)
        return npimage 
        print('retrieved image as numpy array with dimensions:', npimage.shape)
        #image.show()
        plt.imshow(npimage)
        plt.plot([200,500], [300,-100], lw=5, c='k')
        plt.show()



        # TODO  http://www.scipy-lectures.org/advanced/image_processing/#blurring-smoothing
        # display with polynomially curved paths, 
        # linear convolve, 
        # linearize along the paths, (possibly subtract background?)
        # generate polynomial x-axis
        # stitch smoothly
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
Exemplo n.º 37
0
	def capture_bulb(self, test = False, callback = None):
		if test:
			sec = self.status['test-exp-sec']

			self.set_config_value_checked('iso', self.status['test-iso'])
			try:
				self.status['test-iso'] = int(self.get_config_value('iso'))
			except:
				pass
			self.set_config_choice('capturetarget', 0) #mem
			self.set_config_choice('imageformat', 1) #Large Normal JPEG
		else:
			sec = self.status['exp-sec']

			self.set_config_value_checked('iso', self.status['iso'])
			try:
				self.status['iso'] = int(self.get_config_value('iso'))
			except:
				pass
			self.set_config_choice('capturetarget', 1) #card
			#self.set_config_choice('imageformat', 24) #RAW 
			self.set_config_choice('imageformat', 7) #RAW + Large Normal JPEG 

		self.set_config_value('aperture', self.status['f-number'])
		self.status['f-number'] = self.get_config_value('aperture')

		if sec <= 30:
			bulbmode = None
			self.set_config_value_checked('autoexposuremode', 'Manual')
			self.set_config_value_checked('shutterspeed', sec)
			gp.check_result(gp.gp_camera_trigger_capture(self.camera, self.context))
			
		else:
			self.set_config_value_checked('autoexposuremode', 'Manual')
			if not self.set_config_value_checked('shutterspeed', 'Bulb'):
				self.set_config_value_checked('autoexposuremode', 'Bulb')
		
			bulbmode = 'eosremoterelease'
			if not self.set_config_value_checked('eosremoterelease', 'Immediate'):
				self.set_config_value('bulb', 1)
				bulbmode = 'bulb'
		self.t_start = time.time()
		t = 0
		self.status['exp_in_progress'] = True
		self.status['interrupt'] = False
		while True:
			if t < sec - 4 and not self.status['interrupt']:
				time.sleep(3)
			e, file_path =  gp.check_result(gp.gp_camera_wait_for_event(self.camera, 1000,self.context))
			t = time.time() - self.t_start
			print "camera event ", t, e, file_path
			
			if self.status['exp_in_progress']:
				self.status['cur_time'] = int(t)

			if self.status['exp_in_progress'] and (t > sec or self.status['interrupt']):
				if bulbmode == 'bulb':
					self.set_config_value('bulb', 0)
				elif  bulbmode == 'eosremoterelease':
					self.set_config_value_checked('eosremoterelease', 'Release Full')
				self.status['exp_in_progress'] = False

			
			if e == gp.GP_EVENT_FILE_ADDED:
				print >> sys.stderr, "filepath:", file_path.folder, file_path.name
				filename, file_extension = os.path.splitext(file_path.name)
				if file_extension == ".jpg" or file_extension == ".JPG":
					break
		
		self.status['exp_in_progress'] = False
		self.status['cur_time'] = 0
		self.status['interrupt'] = False
	
		target = os.path.join('/tmp', file_path.name)
		
		n = 20
		while True:
			n -= 1
			try:
				camera_file = gp.check_result(gp.gp_camera_file_get(self.camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, self.context))
				file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
				if callback is not None:
					callback(file_data)
				break
			except gp.GPhoto2Error as ex:
				if ex.code == gp.GP_ERROR_CAMERA_BUSY:
					time.sleep(1)

					if (n > 0):
						continue
				raise

		#stop review on display
		self.set_config_value_checked('eosremoterelease', 'Press Half')
		self.set_config_value_checked('eosremoterelease', 'Release Half')
	
		self.do_fps_hack()