Example #1
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
Example #2
0
def capture_frame(camera, context):
    error, file = gp.gp_camera_capture_preview(camera, context)
    if error != 0:
        print(gp.gp_result_as_string(error))
    gp.gp_file_save(file, "photo.jpg")
    photo = cv2.imread("photo.jpg")
    return photo
Example #3
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))
Example #4
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
Example #5
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)
Example #6
0
 def _do_preview(self):
     # capture preview image
     OK, camera_file = gp.gp_camera_capture_preview(self.camera)
     if OK < gp.GP_OK:
         print('Failed to capture preview')
         self.running = False
         return
     self._send_file(camera_file)
 def _do_preview(self):
     # capture preview image
     OK, camera_file = gp.gp_camera_capture_preview(self.camera)
     if OK < gp.GP_OK:
         print('Failed to capture preview')
         self.running = False
         return
     self._send_file(camera_file)
Example #8
0
 def _do_preview(self):
     # capture preview image (not saved to camera memory card)
     OK, camera_file = gp.gp_camera_capture_preview(self.camera, self.context)
     if OK < gp.GP_OK:
         print('Failed to capture preview')
         self.running = False
         return
     self._send_file(camera_file)
Example #9
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)
Example #10
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
Example #11
0
def get_preview_as_image(camera, raw=False):
    OK, camera_file = gp.gp_camera_capture_preview(camera)
    if OK == gp.GP_OK:
        file_data = camera_file.get_data_and_size()
        if raw:
            return io.BytesIO(file_data)
        else:
            image = Image.open(io.BytesIO(file_data))
            image.load()
            return image
Example #12
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
Example #13
0
 def capture_preview(self, save_to = None):
     self.log("Capturing preview")
     if not self.in_preview:
         self.enter_preview()
     camerafile = gp.check_result(gp.gp_camera_capture_preview(
             self.camera,
             self.context))
     if save_to is not None:
         camerafile.save(save_to)
     return camerafile
Example #14
0
 def __init__(self):
     self.PHOTO_DIR = os.path.expanduser(
         '~/Documents/photobooth/backend-server/photos')
     self.file_cache = None
     logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                         level=logging.WARNING)
     gp.check_result(gp.use_python_logging())
     self.camera = gp.check_result(gp.gp_camera_new())
     gp.check_result(gp.gp_camera_init(self.camera))
     gp.check_result(gp.gp_camera_capture_preview(self.camera))
     self.use_cached = False
Example #15
0
 def __init__(self):
     self.do_next = QtCore.QEvent.registerEventType()
     super(CameraHandler, self).__init__()
     self.running = False
     # initialise camera
     self.context = gp.Context()
     self.camera = gp.Camera()
     self.camera.init(self.context)
     # get camera config tree
     self.config = self.camera.get_config(self.context)
     self.old_capturetarget = None
     # get the camera model
     OK, camera_model = gp.gp_widget_get_child_by_name(
         self.config, 'cameramodel')
     if OK < gp.GP_OK:
         OK, camera_model = gp.gp_widget_get_child_by_name(
             self.config, 'model')
     if OK >= gp.GP_OK:
         self.camera_model = camera_model.get_value()
         print('Camera model:', self.camera_model)
     else:
         print('No camera model info')
         self.camera_model = ''
     if self.camera_model == 'unknown':
         # 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(
             self.config, 'capturesizeclass')
         if OK >= gp.GP_OK:
             # set value
             value = capture_size_class.get_choice(2)
             capture_size_class.set_value(value)
             # set config
             self.camera.set_config(self.config, self.context)
     else:
         # put camera into preview mode to raise mirror
         gp.gp_camera_capture_preview(self.camera, self.context)
Example #16
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
Example #17
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
Example #18
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
Example #19
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
    def streamLoop(self):
        path = piggyphoto.CameraFilePath()
        cfile = piggyphoto.cameraFile()

        ans = 0
        for i in range(1 + 1000):
            ans = gp.gp_camera_capture_preview(self.camera, self.context)
            if ans == 0: break
            else: print "capture_preview(%s) retry #%d..." % (destpath, i)
        #check(ans)
        print ">>>>", ans

        #if destpath:
        #    cfile.save(destpath)
        #else:
        #    return cfile

        print "loop"
 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)
Example #22
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
Example #23
0
 def put_camera_capture_preview_mirror(self, camera, camera_config,
                                       camera_model):
     if camera_model == 'unknown':
         # 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(
             camera_config, 'capturesizeclass')
         print(OK, capture_size_class)
         if OK >= gp.GP_OK:
             # set value
             value = capture_size_class.get_choice(2)
             capture_size_class.set_value(value)
             # set config
             camera.set_config(camera_config)
     else:
         # put camera into preview mode to raise mirror
         ret = gp.gp_camera_capture_preview(camera)  # OK, camera_file
         print(
             ret
         )  # [0, <Swig Object of type 'CameraFile *' at 0x7fb5a0044a40>]
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
Example #25
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
Example #26
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))
Example #27
0
    def fetch_preview(self):
        '''
        Holt ein einzelnes Vorschaubild von der Kamera
        '''
        if debug:
            self.index += 1
            time.sleep(0.2)
            if (self.index % 3) == 0:
                file = const.IMG_PATH + '/test1.jpg'
            elif (self.index % 3) == 1:
                file = const.IMG_PATH + '/test2.jpg'
            else:
                file = const.IMG_PATH + '/test3.jpg'
            return io.FileIO(file).read()
        else:
            next_image = self.check_success(
                gp.gp_camera_capture_preview(self.cam), "Preview", True)
            if self.last_success:
                self.last_preview = next_image

            # capture preview image (not saved to camera memory card)
            return self.prepare_pixmap(self.last_preview)
Example #28
0
 def run(self):
     self.plugged = True
     logging.debug('Camera running')
     while True:
         last_grab = time.time()
         if config.run == False:
             self.stop()
             break
         OK, self.camera_file = gp.gp_camera_capture_preview(self.camera)
         if config.trigger == True:
             config.devices[self.name + str(self.index)] = False
             logging.debug("Gphoto camera triggered")
             self.t = time.time()
             if OK < gp.GP_OK:
                 print('Failed to capture preview')
             self.filename = config.experiment_path + config.status + "/g" + "_" + str(
                 config.count).zfill(4) + "_" + str(self.index) + ".png"
             self.q.put([self.t, self.filename])
             file_data = self.camera_file.get_data_and_size()
             self.save_frame_q.put([self.filename, file_data])
             self.empty_queue()
             config.devices[self.name + str(self.index)] = True
Example #29
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
Example #30
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()
Example #31
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
Example #32
0
    def get_video_thread(self, stop):
        self.go_button.setEnabled(False)
        self.stop_button.setEnabled(True)
        self.record_flag.setEnabled(False)
        self.record_file.setEnabled(False)
        self.video_flag.setEnabled(False)
        if self.record_flag.checkState() == QtCore.Qt.Checked:
            fourcc = 0x00000000 #cv2.cv.CV_FOURCC('r', 'a', 'w', ' ')
            out = cv2.VideoWriter()
            file_counter = 1
            filename = str(self.record_file.text())
            name, extension = os.path.splitext(filename)
            while os.path.isfile(filename):
              filename = name+'-'+str(file_counter).zfill(4)+'.avi'
              file_counter = file_counter + 1
            out.open(filename,fourcc, 24, (768,512), True)

        framecount = 0
        start_time = time.time()
        while not stop.isSet():
            if framecount == 30:
                self.text_line.setText('Video '+str(int(30/(time.time()-start_time)))+' fps')
                start_time = time.time()
                framecount = 0
            error, image = gphoto2.gp_camera_capture_preview(self.camera, self.context)
            data = image.get_data_and_size()
            array = numpy.fromstring(memoryview(data).tobytes(), dtype=numpy.uint8)
            img = cv2.imdecode(array, 1)
            if  int(self.zoom_select.currentText()) != 1:
                x = img.shape[0]
                y = img.shape[1]
                zoom = int(self.zoom_select.currentText())
                img = cv2.resize(img[x*(zoom-1)/(2*zoom):x*(zoom+1)/(2*zoom),y*(zoom-1)/(2*zoom):y*(zoom+1)/(2*zoom),:], (768,512))
            if self.record_flag.checkState() == QtCore.Qt.Checked:
                out.write(img)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            
            if self.contours_flag.checkState() == QtCore.Qt.Checked:
                img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#                img_gray = cv2.medianBlur(img_gray, 5)
#                thresh = cv2.adaptiveThreshold(img_gray ,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
                ret, thresh = cv2.threshold(img_gray, self.contours_slider.value() , 255, cv2.THRESH_BINARY)
                contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
                cv2.drawContours(img, contours, -1, (255,255,255), 1)
                area = 0
                for i in contours:
                    area = area+cv2.contourArea(i)
#                print area

            if self.reticle_flag.checkState() == QtCore.Qt.Checked:
                cv2.line(img, (768/2,0),(768/2,512),(255,255,255),1)
                cv2.line(img, (0,512/2),(768,512/2),(255,255,255),1)
                for i in range(30, 500, 100):
                    cv2.circle(img, (768/2,512/2), i, (255,255,255), 1)


            if self.lock_paint == 0:
                self.myImage = QtGui.QImage(img, 768, 512, QtGui.QImage.Format_RGB888)
                framecount = framecount + 1
                self.image_event = 1
                self.update()

        if self.record_flag.checkState() == QtCore.Qt.Checked:
            out.release()
        gphoto2.gp_camera_exit(self.camera, self.context)
        self.record_flag.setEnabled(True)
        self.record_file.setEnabled(True)
        self.video_flag.setEnabled(True)
        stop.clear()
        self.text_line.setText('Video stopped')
        self.go_button.setEnabled(True)
        self.stop_button.setEnabled(False)
def get_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))
  buf = io.BytesIO(file_data)
  buf.seek(0)
  return buf
Example #34
0
upper_green=np.array([80,255,255]) # 35-77为绿色的范围

# 全屏窗口=============
cv.namedWindow('上海金融中心', 0)
cv.resizeWindow('上海金融中心', cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN) #画面全屏
cv.setWindowProperty('上海金融中心', cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN) #窗口全屏

# 初始化帧率
count = 0
# 基准时间
t0 = time.time()
flag = 0

while(True):
    # 获取预览照片
    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)
    frame = cv.flip(frame,1,dst=None)
    frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # 转灰度图
    greenToBg()    # 调用更换合成绿幕背景
    if image_width > 900:
        # canon 600D 1050x704, 500D 928x616
        small_frame = cv.resize(gray, (0, 0), fx=scale_factor, fy=scale_factor)
    else:
        small_frame = gray

    # 计算当前的fps帧率
    t1 = int(time.time())
Example #35
0
    def do_GET(self):                
        # Respond to mjpg GET requests
        if self.path[:12] == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        if self.path[:16] == '/slr_stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            try:
                while True:
                    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?
                    data = memoryview(file_data)
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(data))
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    self.wfile.write(data)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        # Respond to still jpg GET requests
        elif self.path[:10] == "/still.jpg":
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Access-Control-Allow-Origin', '*')
            try:
                with output.condition:
                    output.condition.wait()
                    frame = output.frame
                self.send_header('Content-Type', 'image/jpeg')
                self.send_header('Content-Length', len(frame))
                self.end_headers()
                self.wfile.write(frame)
                self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))        

        elif self.path[:14] == "/slr_still.jpg":
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Access-Control-Allow-Origin', '*')
            try:
                with output.condition:
                    output.condition.wait()
                    frame = output.frame
                self.send_header('Content-Type', 'image/jpeg')
                self.send_header('Content-Length', len(frame))
                self.end_headers()
                self.wfile.write(frame)
                self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))        


        elif self.path[:2] == '/?':
            # Send response status code
            self.send_response(200)
            # Send headers
            self.send_header('Content-type','text/html')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()

            # Prepare response object
            resp_obj = {'action': 'null', 'crop':camera.crop, 'result':'true'}
            
            # Parse incoming params
            params = dict(urllib.parse.parse_qsl(self.path.split("?")[1], True))
            for key,value in params.items():
                logging.info(key + " = " + value)

            # Param actions (route to app logic)
            if("action" in params):
                if(params.get("action") == "abspos"):
                    resp_obj["action"] = "abspos"
                    resp_obj["result"] = "true"
                    resp_obj["crop"] = CameraControl.setAbsolutePosition(params.get("crop"))

                elif(params.get("action") == "relpos"):
                    
                    hasSuccess, newCrop = CameraControl.setRelativePosition(params.get("crop"))

                    # result obj
                    resp_obj["action"] = "relpos"
                    resp_obj["result"] = hasSuccess
                    resp_obj["crop"] = newCrop

                elif(params.get("action") == "zoom"):                    
                    
                    hasSuccess, newCrop = CameraControl.setZoom(params.get("factor"))

                    # result obj
                    resp_obj["action"] = "zoom"
                    resp_obj["result"] = hasSuccess
                    resp_obj["crop"] = newCrop

                elif(params.get("action") == "reboot"):
                    
                    CameraControl.doReboot()

                    #result obj
                    resp_obj["action"] = "reboot"
                    resp_obj["result"] = "true"
                    del resp_obj["crop"]

                elif(params.get("action") == "shutdown"):
                    
                    CameraControl.doShutdown()

                    #result obj
                    resp_obj["action"] = "shutdown"
                    resp_obj["result"] = "true"
                    del resp_obj["crop"]

                elif(params.get("action") == "update"):

                    logging.info("UPDATE - not implemented")
                    
                    #result obj
                    resp_obj["action"] = "update"
                    resp_obj["result"] = "false"
                    del resp_obj["crop"]
                    
            self.wfile.write(bytes(json.dumps(resp_obj), 'utf8'))    
        else:
            logging.info("Path requested: " +self.path)
            self.send_error(404)
            self.end_headers()
def capture_preview(camera, context, filename='capture_preview.jpg'):
        """ Capture a preview image """
        camfile = gp.check_result(gp.gp_file_new())
        gp.gp_camera_capture_preview(camera, camfile, context)
        gp.gp_file_save(camfile, 'capture_preview.jpg')
        gp.gp_file_unref(camfile)