def _raw2img(self):
        ''' decode raw data to obtain bayer image and settings data '''

        # skip if calibrated json file already exists, otherwise perform centroid calibration
        if self._raw_data:

            from plenopticam.lfp_reader.lfp_decoder import LfpDecoder

            # decode raw data
            obj = LfpDecoder(self._raw_data, self.cfg, self.sta)
            obj.decode_raw()
            self._wht_img = obj.rgb_img
            del obj

        return True
    def _raw2img(self):
        ''' decode raw data to obtain bayer image and settings data '''

        # skip if calibrated json file already exists, otherwise perform centroid calibration
        if self._raw_data:

            # decode raw data
            obj = LfpDecoder(self._raw_data, self.cfg, self.sta)
            obj.decode_raw()
            self._wht_bay = obj.bay_img
            del obj

            # balance Bayer channels in white image
            try:
                wht_json = json.loads(self._wht_json.read())
                frame_arr = safe_get(wht_json, 'master', 'picture',
                                     'frameArray')[0]
                self.cfg.lfpimg['ccm_wht'] = safe_get(frame_arr, 'frame',
                                                      'metadata', 'image',
                                                      'color',
                                                      'ccmRgbToSrgbArray')
                awb = safe_get(frame_arr, 'frame', 'metadata', 'devices',
                               'sensor', 'normalizedResponses')[0]
                gains = [
                    1. / awb['b'], 1. / awb['r'], 1. / awb['gr'],
                    1. / awb['gb']
                ]
                self.cfg.lfpimg['awb_wht'] = gains
            except ValueError:
                gains = [
                    1 / 0.74476742744445801, 1 / 0.76306647062301636, 1, 1
                ]

            # apply white balance gains to calibration file
            cfa_obj = CfaProcessor(bay_img=self._wht_bay,
                                   cfg=self.cfg,
                                   sta=self.sta)
            cfa_obj.set_gains(gains)
            self._wht_bay = cfa_obj.apply_awb()
            del cfa_obj

        return True
Exemple #3
0
    def load_lfp_metadata(self):
        """ load LFP metadata settings (for Lytro files only) """

        fname = os.path.splitext(os.path.basename(self.cfg.params[self.cfg.lfp_path]))[0]+'.json'
        fp = os.path.join(self.cfg.exp_path, fname)
        if os.path.isfile(fp):
            json_dict = self.cfg.load_json(fp=fp, sta=None)
            from plenopticam.lfp_reader.lfp_decoder import LfpDecoder
            self.cfg.lfpimg = LfpDecoder().filter_lfp_json(json_dict, settings=self.cfg.lfpimg)

        return True
Exemple #4
0
    def decode_lytro_file(self):

        # Lytro type decoding
        with open(self._lfp_path, mode='rb') as file:

            # LFC and raw type decoding
            obj = LfpDecoder(file, self.cfg, self.sta, lfp_path=self._lfp_path)
            obj.main()
            self._lfp_img = obj.bay_img
            self._json_dict = obj.json_dict
            del obj

            # save bayer image as file (if not already present)
            if not os.path.exists(self.fp) and not self.sta.interrupt:
                self.sta.status_msg(msg='Save raw image',
                                    opt=self.cfg.params[self.cfg.opt_prnt])
                self.sta.progress(None, self.cfg.params[self.cfg.opt_prnt])
                misc.save_img_file(misc.Normalizer(
                    self._lfp_img).uint16_norm(),
                                   self.fp,
                                   file_type='tiff')
                self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])

        return True
Exemple #5
0
    def main(self):

        # check interrupt status
        if self.sta.interrupt:
            return False

        if self._lfp_path.lower().endswith(SUPP_FILE_EXT):

            try:
                self.decode_lytro_file()
            except FileNotFoundError:
                # print status
                self.sta.status_msg(
                    '{0} not found'.format(os.path.basename(self._lfp_path)),
                    self.cfg.params[self.cfg.opt_prnt])
                self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])
                self.sta.error = True
            except Exception as e:
                # unrecognized LFP file type
                if not self._json_dict:
                    raise LfpTypeError(e)
                else:
                    raise PlenopticamError(e)
        else:
            try:
                # read and decode generic image file type
                self._lfp_img = misc.load_img_file(self._lfp_path)
                # inverse sRGB conversion
                self._lfp_img = GammaConverter().srgb_conv(self._lfp_img,
                                                           inverse=True)
            except TypeError:
                self.sta.status_msg('File type not recognized')
                self.sta.error = True
                return False

            try:
                # try to load json file (if present)
                json_dict = self.cfg.load_json(self._lfp_path)
                self.cfg.lfpimg = LfpDecoder.filter_lfp_json(
                    json_dict, self.cfg.lfp_img)
            except:
                pass

        # write json file
        self.cfg.save_params()

        return True
    def load_pickle_file(self):

        # file path
        fp = join(self.cfg.exp_path, 'lfp_img_align.pkl')

        try:
            # load previously computed light field alignment
            self.lfp_img_align = pickle.load(open(fp, 'rb'))
        except EOFError:
            os.remove(fp)

        # load LFP metadata settings (for Lytro files only)
        fp = join(
            self.cfg.exp_path,
            splitext(basename(self.cfg.params[self.cfg.lfp_path]))[0] +
            '.json')
        if os.path.isfile(fp):
            json_dict = self.cfg.load_json(fp=fp, sta=None)
            from plenopticam.lfp_reader.lfp_decoder import LfpDecoder
            self.cfg.lfpimg = LfpDecoder().filter_lfp_json(
                json_dict, settings=self.cfg.lfpimg)
Exemple #7
0
    def _search_cal_dirs(self):
        """ look for geo data in calibration folders """

        # skip if file already found or if provided path is not a directory
        if not self._file_found:
            onlydirs = [d for d in listdir(self._path)]
            items = [self._serial] if onlydirs.count(
                self._serial) else onlydirs

            # iterate through directories
            for item in items:
                cali_manifest = join(join(self._path, item),
                                     'cal_file_manifest.json')
                if exists(cali_manifest):
                    with open(cali_manifest, 'r') as file:
                        # find matching sha-1 value
                        json_dict = json.load(file)
                        self._match_georef(json_dict)
                        if self._file_found:
                            # update config and load raw data
                            self.cfg.params[self.cfg.cal_meta] = join(
                                join(self._path.split('.')[0], self._serial),
                                self._cal_fn)
                            with open(self.cfg.params[self.cfg.cal_meta],
                                      mode='rb') as meta_file:
                                self._raw_data = meta_file.read()
                            break

                # extract Lytro's 1st generation files
                elif item.lower().endswith(SUPP_FILE_EXT[-4:]):
                    fn = join(join(self._path, item))
                    if not exists(splitext(fn)[0]):
                        # status update
                        self.sta.status_msg('Extract ' + basename(fn),
                                            self.cfg.params[self.cfg.opt_prnt])
                        # bundle type decoding
                        with open(fn, mode='rb') as file:
                            obj = LfpDecoder(file,
                                             self.cfg,
                                             self.sta,
                                             lfp_path=fn)
                            obj.main()
                            del obj

                    # find matching file
                    mod_txts = [
                        d for d in listdir(splitext(fn)[0])
                        if d.lower().startswith('mod')
                        and d.lower().endswith('.txt')
                    ]
                    for mod_txt in mod_txts:
                        with open(join(splitext(fn)[0], mod_txt), 'r') as f:
                            json_dict = {}
                            json_dict.update(
                                json.loads(f.read().rpartition('}')[0] + '}'))
                            #self._match_georef(json_dict['master']['picture']['frameArray'][0])
                            #if json_dict['master']['picture']['frameArray'][0]['frame']['imageRef'] == self._georef:
                            if json_dict['master']['picture'][
                                    'derivationArray'] == self._georef:
                                self._file_found = True

        return True
Exemple #8
0
    def main(self):

        if self._lfp_path.endswith(('.lfp', '.lfr', '.raw') + tuple('.c.'+str(num) for num in (0, 1, 2, 3))):

            # filename and file path from previously decoded data
            dp = os.path.splitext(self._lfp_path)[0]
            fn = os.path.basename(dp)+'.tiff'
            fp = os.path.join(dp, fn)

            # load previously generated tiff if present
            if os.path.exists(fp):
                try:
                    self._lfp_img = misc.load_img_file(fp)
                except TypeError as e:
                    self.sta.status_msg(e, self.cfg.params[self.cfg.opt_prnt])
                    self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])
                    raise LfpTypeError(e)
                except FileNotFoundError as e:
                    # print status
                    self.sta.status_msg('File {0} not found'.format(self._lfp_path), self.cfg.params[self.cfg.opt_prnt])
                    self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])
                    raise PlenopticamError(e)

            else:
                try:
                    # Lytro type decoding
                    with open(self._lfp_path, mode='rb') as file:

                        # print status
                        self.sta.status_msg('Decode Lytro image file', self.cfg.params[self.cfg.opt_prnt])
                        self.sta.progress(None, self.cfg.params[self.cfg.opt_prnt])

                        # LFC and raw type decoding
                        obj = LfpDecoder(file, self.cfg, self.sta)
                        if self._lfp_path.endswith(('.lfp', '.lfr') + tuple('.c.'+str(num) for num in (0, 1, 2, 3))):
                            # LFC type decoding
                            obj.decode_lfc()
                            self.cfg.save_json(os.path.join(dp, os.path.basename(dp)+'.json'), json_dict=obj.json_dict)
                        elif self._lfp_path.endswith('.raw'):
                            # raw type decoding
                            obj.decode_raw()
                        self._lfp_img = obj.rgb_img
                        del obj

                        # save bayer image as file
                        misc.save_img_file(misc.uint16_norm(self._lfp_img), fp, type='tiff')

                        # print status
                        self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])

                except FileNotFoundError as e:
                    # print status
                    self.sta.status_msg('File {0} not found'.format(self._lfp_path), self.cfg.params[self.cfg.opt_prnt])
                    self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])
                    raise PlenopticamError(e)
        else:
            try:
                # read and decode generic image file type
                self._lfp_img = misc.load_img_file(self._lfp_path)
            except TypeError as e:
                raise LfpTypeError(e)

            try:
                # try to load json file (if present)
                json_dict = self.cfg.load_json(self._lfp_path)
                self.cfg.lfpimg = LfpDecoder.filter_json(json_dict)
            except:
                pass

        # write json file
        self.cfg.save_params()

        return True
Exemple #9
0
    def main(self):

        if self._lfp_path.lower().endswith(SUPP_FILE_EXT):

            # filename and file path from previously decoded data
            dp = os.path.splitext(self._lfp_path)[0]
            fn = os.path.basename(dp) + '.tiff'
            fp = os.path.join(dp, fn)

            # load previously generated tiff if present
            if os.path.exists(fp):
                try:
                    self._lfp_img = misc.load_img_file(fp)
                except FileNotFoundError:
                    # print status
                    self.sta.status_msg(
                        '{0} not found'.format(os.path.basename(
                            self._lfp_path)),
                        self.cfg.params[self.cfg.opt_prnt])
                    self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])
                    self.sta.error = True
                except TypeError as e:
                    self.sta.status_msg(e, self.cfg.params[self.cfg.opt_prnt])
                    self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])
                    raise LfpTypeError(e)

            else:
                try:
                    # Lytro type decoding
                    with open(self._lfp_path, mode='rb') as file:

                        # LFC and raw type decoding
                        obj = LfpDecoder(file, self.cfg, self.sta)
                        if self._lfp_path.lower().endswith(SUPP_FILE_EXT[1:]):
                            # LFC type decoding
                            obj.decode_lfc()
                            self.cfg.save_json(os.path.join(
                                dp,
                                os.path.basename(dp) + '.json'),
                                               json_dict=obj.json_dict)
                        elif self._lfp_path.lower().endswith(SUPP_FILE_EXT[0]):
                            # raw type decoding
                            obj.decode_raw()
                        self._lfp_img = obj.rgb_img
                        del obj

                        # save bayer image as file
                        self.sta.status_msg(
                            msg='Save raw image',
                            opt=self.cfg.params[self.cfg.opt_prnt])
                        self.sta.progress(None,
                                          self.cfg.params[self.cfg.opt_prnt])
                        misc.save_img_file(misc.Normalizer(
                            self._lfp_img).uint16_norm(),
                                           fp,
                                           file_type='tiff')
                        self.sta.progress(100,
                                          self.cfg.params[self.cfg.opt_prnt])

                except FileNotFoundError:
                    # print status
                    self.sta.status_msg(
                        '{0} not found'.format(os.path.basename(
                            self._lfp_path)),
                        self.cfg.params[self.cfg.opt_prnt])
                    self.sta.progress(100, self.cfg.params[self.cfg.opt_prnt])
                    self.sta.error = True
                except Exception as e:
                    # unrecognized LFP file type
                    if not obj.json_dict:
                        raise LfpTypeError(e)
                    else:
                        raise PlenopticamError(e)
        else:
            try:
                # read and decode generic image file type
                self._lfp_img = misc.load_img_file(self._lfp_path)
            except TypeError as e:
                raise LfpTypeError(e)

            try:
                # try to load json file (if present)
                json_dict = self.cfg.load_json(self._lfp_path)
                self.cfg.lfpimg = LfpDecoder.filter_json(json_dict)
            except:
                pass

        # write json file
        self.cfg.save_params()

        return True