Ejemplo n.º 1
0
    def test_lfp(self):

        # set config for unit test purposes
        cfg = PlenopticamConfig()
        cfg.params[cfg.opt_dbug] = True

        for fn_lfp, fn_wht in zip(self.fnames_lfp, self.fnames_wht):

            # update file paths and calibration data in config
            cfg.params[cfg.lfp_path] = os.path.join(self.fp, fn_lfp)
            cfg.params[cfg.cal_path] = os.path.join(self.fp, fn_wht)
            cfg.params[cfg.cal_meta] = os.path.splitext(
                cfg.params[cfg.cal_path])[0] + '.json'
            cfg.load_cal_data()

            # create folder (if it doesn't already exist)
            misc.mkdir_p(os.path.splitext(cfg.params[cfg.lfp_path])[0])

            # test light field alignment
            lfp_img = misc.load_img_file(cfg.params[cfg.lfp_path])
            lfp_obj = LfpAligner(lfp_img=lfp_img, cfg=cfg, sta=None)
            ret_val = lfp_obj.main()
            lfp_img = lfp_obj.lfp_img
            del lfp_obj

            # assertion
            self.assertEqual(True, ret_val)

            # test light field extraction
            lfp_obj = LfpExtractor(lfp_img_align=lfp_img, cfg=cfg, sta=None)
            ret_val = lfp_obj.main()
            del lfp_obj

            # assertion
            self.assertEqual(True, ret_val)
Ejemplo n.º 2
0
    def test_cal(self):

        # set config for unit test purposes
        sta = PlenopticamStatus()
        cfg = PlenopticamConfig()
        cfg.reset_values()
        cfg.params[cfg.opt_dbug] = False
        cfg.params[cfg.opt_prnt] = True

        for fn_lfp, fn_wht in zip(self.fnames_lfp, self.fnames_wht):

            # update file paths and calibration data in config
            cfg.params[cfg.lfp_path] = os.path.join(self.fp, fn_lfp)
            cfg.params[cfg.cal_path] = os.path.join(self.fp, fn_wht)

            # create folder (if it doesn't already exist)
            mkdir_p(os.path.splitext(cfg.params[cfg.lfp_path])[0])

            # test light field calibration
            wht_img = load_img_file(cfg.params[cfg.cal_path])
            cal_obj = LfpCalibrator(wht_img=wht_img, cfg=cfg, sta=sta)
            ret_val = cal_obj.main()
            del cal_obj

            # assertion
            self.assertEqual(True, ret_val)
Ejemplo n.º 3
0
    def test_custom_cal(self):

        for fn_lfp, fn_wht in zip(self.loader.opex_fnames_lfp,
                                  self.loader.opex_fnames_wht):

            # generate console output to prevent abort in Travis CI
            print(fn_wht)

            # update file paths and calibration data in config
            self.cfg.params[self.cfg.lfp_path] = join(self.fp, fn_lfp)
            self.cfg.params[self.cfg.cal_path] = join(self.fp, fn_wht)

            # create folder (if it doesn't already exist)
            mkdir_p(splitext(self.cfg.params[self.cfg.lfp_path])[0])

            # test light field calibration
            wht_img = load_img_file(self.cfg.params[self.cfg.cal_path])
            cal_obj = LfpCalibrator(wht_img=wht_img,
                                    cfg=self.cfg,
                                    sta=self.sta)
            ret_val = cal_obj.main()
            del cal_obj

            # assertion
            self.assertEqual(True, ret_val)
Ejemplo n.º 4
0
def crop_imgs(folder, coords_lists):

    img_tiles, files = list(), list()
    exts = ('tif', 'tiff', 'png')

    misc.mkdir_p(os.path.join(folder, 'auto-crop'))
    files = [
        f for f in os.listdir(folder)
        if f.endswith(exts) and not f.startswith('.')
    ]
    files.sort()

    for i, file in enumerate(files):
        coords_nested = coords_lists[i]
        for j, coords in enumerate(coords_nested):
            if coords[0] != 0 and coords[1] != 0:
                cy, cx, h, w = coords
                img = misc.load_img_file(os.path.join(folder, file))
                tile = img[cy - h // 2:cy + h // 2, cx - w // 2:cx + w // 2,
                           ...]
                img_tiles.append(tile)
                fn, ext = os.path.splitext(file)
                misc.save_img_file(tile,
                                   os.path.join(folder, 'auto-crop',
                                                fn + '_crop' + str(j)),
                                   'png',
                                   tag=True)

    return img_tiles, files
Ejemplo n.º 5
0
def get_list(img_dir, vp=1):

    from plenopticam import misc
    import numpy as np

    dir_list = os.listdir(img_dir)
    dir_list.sort()
    img_list = []
    for i in dir_list:
        img_path = os.path.join(img_dir, i)
        ext = img_path.split('.')[::-1][0].lower()
        if ext in [gen_ext.replace('*.', '') for gen_ext in GENERIC_EXTS]:

            # load image
            img = misc.load_img_file(img_path)

            # convert to uint8 if necessary
            img = Normalizer(
                img=img).uint8_norm() if str(img.dtype) != 'uint8' else img

            # append to image list
            img_list.append((i, img))

    # sort image list by indices in file names
    img_tuples = sorted(img_list,
                        key=lambda k: idx_str_sort(k[0], 1 if vp else 0))
    _, img_list = zip(*img_tuples)

    if vp:
        vp_dim = int(np.sqrt(len(img_list)))
        img_list = np.reshape(img_list,
                              newshape=(vp_dim, vp_dim) + img_list[0].shape,
                              order='C')

    return img_list
Ejemplo n.º 6
0
    def test_cal(self):

        # set config for unit test purposes
        sta = PlenopticamStatus()
        cfg = PlenopticamConfig()
        cfg.reset_values()
        cfg.params[cfg.opt_dbug] = False
        cfg.params[
            cfg.
            opt_prnt] = False  # prevent Travis CI to terminate after reaching 4MB logfile size
        cfg.params[cfg.opt_vign] = False
        cfg.params[cfg.opt_sat_] = True

        for fn_lfp, fn_wht in zip(self.fnames_lfp, self.fnames_wht):

            # generate console output to prevent abort in Travis CI
            print(fn_wht)

            # update file paths and calibration data in config
            cfg.params[cfg.lfp_path] = os.path.join(self.fp, fn_lfp)
            cfg.params[cfg.cal_path] = os.path.join(self.fp, fn_wht)

            # create folder (if it doesn't already exist)
            mkdir_p(os.path.splitext(cfg.params[cfg.lfp_path])[0])

            # test light field calibration
            wht_img = load_img_file(cfg.params[cfg.cal_path])
            cal_obj = LfpCalibrator(wht_img=wht_img, cfg=cfg, sta=sta)
            ret_val = cal_obj.main()
            del cal_obj

            # assertion
            self.assertEqual(True, ret_val)
Ejemplo n.º 7
0
    def test_pitch_estimator(self):

        from plenopticam.lfp_calibrator import PitchEstimator

        fns = [join(self.CEA_PATH, fn+'.png') for fn in ['a', 'b', 'c', 'd']]
        ref_sizes = [141, 50, 10, 6]

        for fn, ref_size in zip(fns, ref_sizes):
            img = load_img_file(fn)
            obj = PitchEstimator(img=img, cfg=self.cfg)
            obj.main()

            self.assertEqual(ref_size, obj.M)
Ejemplo n.º 8
0
    def test_lfp(self):

        # set config for unit test purposes
        sta = PlenopticamStatus()
        cfg = PlenopticamConfig()
        cfg.reset_values()
        cfg.params[cfg.opt_dbug] = False
        cfg.params[
            cfg.
            opt_prnt] = False  # prevent Travis CI to terminate after reaching 4MB logfile size

        for fn_lfp, fn_wht in zip(self.fnames_lfp, self.fnames_wht):

            # generate console output to prevent abort in Travis CI
            print(fn_lfp)

            # update file paths and calibration data in config
            cfg.params[cfg.lfp_path] = os.path.join(self.fp, fn_lfp)
            cfg.params[cfg.cal_path] = os.path.join(self.fp, fn_wht)
            cfg.params[cfg.cal_meta] = os.path.splitext(
                cfg.params[cfg.cal_path])[0] + '.json'
            cfg.load_cal_data()

            # create folder (if it doesn't already exist)
            mkdir_p(os.path.splitext(cfg.params[cfg.lfp_path])[0])

            # test light field alignment
            lfp_img = load_img_file(cfg.params[cfg.lfp_path])
            lfp_obj = LfpAligner(lfp_img=lfp_img, cfg=cfg, sta=sta)
            ret_val = lfp_obj.main()
            lfp_img = lfp_obj.lfp_img
            del lfp_obj

            # assertion
            self.assertEqual(True, ret_val)

            # test light field extraction
            lfp_obj = LfpExtractor(lfp_img_align=lfp_img, cfg=cfg, sta=sta)
            lfp_obj.main()
            vp_img_arr = lfp_obj.vp_img_arr
            del lfp_obj

            lfp_obj = LfpRefocuser(vp_img_arr=vp_img_arr, cfg=cfg, sta=sta)
            lfp_obj.main()
            del lfp_obj

            # assertion
            self.assertEqual(True, ret_val)
Ejemplo n.º 9
0
    def test_custom_lfp(self):

        for fn_lfp, fn_wht in zip(self.loader.opex_fnames_lfp,
                                  self.loader.opex_fnames_wht):

            # generate console output to prevent abort in Travis CI
            print(fn_lfp)

            # update file paths and calibration data in config
            self.cfg.params[self.cfg.lfp_path] = join(self.fp, fn_lfp)
            self.cfg.params[self.cfg.cal_path] = join(self.fp, fn_wht)
            self.cfg.params[self.cfg.cal_meta] = splitext(
                self.cfg.params[self.cfg.cal_path])[0] + '.json'
            self.cfg.load_cal_data()

            # create folder (if it doesn't already exist)
            mkdir_p(splitext(self.cfg.params[self.cfg.lfp_path])[0])

            # test light field alignment
            lfp_img = load_img_file(self.cfg.params[self.cfg.lfp_path])
            lfp_obj = LfpAligner(lfp_img=lfp_img, cfg=self.cfg, sta=self.sta)
            ret_val = lfp_obj.main()
            lfp_img = lfp_obj.lfp_img
            del lfp_obj

            # assertion
            self.assertEqual(True, ret_val)

            # test light field extraction
            lfp_obj = LfpExtractor(lfp_img_align=lfp_img,
                                   cfg=self.cfg,
                                   sta=self.sta)
            ret_val = lfp_obj.main()
            vp_img_arr = lfp_obj.vp_img_arr
            del lfp_obj

            # assertion
            self.assertEqual(True, ret_val)

            lfp_obj = LfpRefocuser(vp_img_arr=vp_img_arr,
                                   cfg=self.cfg,
                                   sta=self.sta)
            ret_val = lfp_obj.main()
            del lfp_obj

            # assertion
            self.assertEqual(True, ret_val)
Ejemplo n.º 10
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
Ejemplo n.º 11
0
    def test_real_data(self):

        self.depth_map, _ = load_pfm(
            '../examples/data/gradient_rose_close/depth.pfm')
        self.rgb_img = load_img_file(
            '../examples/data/gradient_rose_close/thumbnail.png')
        self.lfp_depth_obj = LfpDepth(depth_map=self.depth_map)

        # test invalid downscale parameters
        for i in range(-1, 5):
            print(i)
            try:
                self.lfp_depth_obj.plot_point_cloud(rgb_img=self.rgb_img,
                                                    down_scale=i)
            except PlenopticamError as e:
                self.assertTrue(e, PlenopticamError)

        # test Axes3D argument
        import matplotlib.pyplot as plt
        fig, ax = plt.figure(), plt.axes(projection='3d')
        self.lfp_depth_obj.plot_point_cloud(down_scale=4,
                                            view_angles=(50, 70),
                                            ax=ax)
Ejemplo n.º 12
0
def main():

    # program info
    print("\nPlenoptiCam v%s \n" % __version__)

    # create config object
    cfg = PlenopticamConfig()
    cfg.default_values()

    # parse options
    cfg = parse_options(sys.argv[1:], cfg)

    # instantiate status object
    sta = misc.PlenopticamStatus()
    sta.bind_to_interrupt(sys.exit)  # set interrupt

    # force relative paths to be absolute
    cfg.params[cfg.lfp_path] = os.path.abspath(cfg.params[cfg.lfp_path])
    cfg.params[cfg.cal_path] = os.path.abspath(cfg.params[cfg.cal_path])

    # collect light field image file name(s) based on provided path
    if os.path.isdir(cfg.params[cfg.lfp_path]):
        lfp_filenames = [
            f for f in os.listdir(cfg.params[cfg.lfp_path])
            if f.lower().endswith(SUPP_FILE_EXT)
        ]
        cfg.params[cfg.lfp_path] = os.path.join(cfg.params[cfg.lfp_path],
                                                'dummy.ext')
    elif not os.path.isfile(cfg.params[cfg.lfp_path]):
        lfp_filenames = [
            misc.select_file(cfg.params[cfg.lfp_path],
                             'Select plenoptic image')
        ]
    else:
        lfp_filenames = [cfg.params[cfg.lfp_path]]

    if not cfg.params[cfg.cal_path]:
        # manual calibration data selection
        sta.status_msg(
            '\r Please select white image calibration source manually',
            cfg.params[cfg.opt_prnt])
        # open selection window (at current lfp file directory) to set calibration folder path
        cfg.params[cfg.cal_path] = misc.select_file(
            cfg.params[cfg.lfp_path], 'Select calibration image')

    # provide number of found images to user
    print("\n %s Image(s) found" % len(lfp_filenames))

    # cancel if file paths not provided
    sta.validate(checklist=lfp_filenames + [cfg.params[cfg.lfp_path]],
                 msg='Canceled due to missing image file path')

    # iterate through light field image(s)
    for lfp_filename in sorted(lfp_filenames):

        # change path to next filename
        cfg.params[cfg.lfp_path] = os.path.join(
            os.path.dirname(cfg.params[cfg.lfp_path]), lfp_filename)
        print(cfg.params[cfg.lfp_path])
        sta.status_msg(msg='Process file ' + lfp_filename,
                       opt=cfg.params[cfg.opt_prnt])

        # remove output folder if option is set
        misc.rmdir_p(cfg.exp_path) if cfg.params[cfg.dir_remo] else None

        try:
            # decode light field image
            lfp_obj = lfp_reader.LfpReader(cfg, sta)
            lfp_obj.main()
            lfp_img = lfp_obj.lfp_img
            del lfp_obj
        except Exception as e:
            misc.PlenopticamError(e)
            continue
        # create output data folder
        misc.mkdir_p(cfg.exp_path, cfg.params[cfg.opt_prnt])

        if cfg.cond_auto_find():
            # automatic calibration data selection
            obj = lfp_calibrator.CaliFinder(cfg, sta)
            obj.main()
            wht_img = obj.wht_bay
            del obj

        else:
            # load white image calibration file
            wht_img = misc.load_img_file(cfg.params[cfg.cal_path])
            # save settings configuration
            cfg.save_params()

        # perform calibration if previously computed calibration data does not exist
        meta_cond = not (os.path.exists(cfg.params[cfg.cal_meta])
                         and cfg.params[cfg.cal_meta].lower().endswith('json'))
        if meta_cond or cfg.params[cfg.opt_cali]:
            # perform centroid calibration
            cal_obj = lfp_calibrator.LfpCalibrator(wht_img, cfg, sta)
            cal_obj.main()
            cfg = cal_obj.cfg
            del cal_obj

        # load calibration data
        cfg.load_cal_data()

        #  check if light field alignment has been done before
        if cfg.cond_lfp_align():
            # align light field
            lfp_obj = lfp_aligner.LfpAligner(lfp_img, cfg, sta, wht_img)
            lfp_obj.main()
            lfp_obj = lfp_obj.lfp_img
            del lfp_obj

        # load previously computed light field alignment
        with open(os.path.join(cfg.exp_path, 'lfp_img_align.pkl'), 'rb') as f:
            lfp_img_align = pickle.load(f)

        # extract viewpoint data
        lfp_calibrator.CaliFinder(cfg).main()
        obj = lfp_extractor.LfpExtractor(lfp_img_align, cfg=cfg, sta=sta)
        obj.main()
        vp_img_arr = obj.vp_img_arr
        del obj

        # do refocusing
        if cfg.params[cfg.opt_refo]:
            obj = lfp_refocuser.LfpRefocuser(vp_img_arr, cfg=cfg, sta=sta)
            obj.main()
            del obj

    return True
Ejemplo n.º 13
0
    crop_opt = False

    score_series = list()
    for i, target_folder in enumerate(target_folders):
        fp = os.path.join(path, target_folder)

        files = [f for f in os.listdir(fp) if f.endswith(exts)]
        files.sort()

        scores = list()
        for file in files:

            # skip file if missing
            if os.path.splitext(file)[0].split('_')[0] not in skip_list:

                img_ref = load_img_file(os.path.join(fp, file))
                if target_folder.startswith('thumb_collection'):
                    img_src = load_img_file(
                        os.path.join(
                            fp, 'other_views',
                            os.path.splitext(file)[0] + '_2_7' + '.png'))
                else:
                    img_src = load_img_file(
                        os.path.join(
                            fp, 'other_views',
                            file.split('__')[0] + '28__' +
                            file.split('__')[1]))

                score = hist_dist(img_ref, img_src)
                scores.append(score)
                print(file + ': %s' % scores[-1])
Ejemplo n.º 14
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
Ejemplo n.º 15
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
Ejemplo n.º 16
0
def main():

    # create config object
    cfg = PlenopticamConfig()
    cfg.default_values()
    cfg.reset_values()

    # parse options
    cfg = parse_options(sys.argv[1:], cfg)

    # instantiate status object
    sta = misc.PlenopticamStatus()
    sta.bind_to_interrupt(sys.exit)  # set interrupt

    # select light field image(s) considering provided folder or file
    if os.path.isdir(cfg.params[cfg.lfp_path]):
        lfp_filenames = [
            f for f in os.listdir(cfg.params[cfg.lfp_path])
            if f.lower().endswith(SUPP_FILE_EXT)
        ]
    elif not os.path.isfile(cfg.params[cfg.lfp_path]):
        lfp_filenames = [
            misc.select_file(cfg.params[cfg.lfp_path],
                             'Select plenoptic image')
        ]
    else:
        lfp_filenames = [cfg.params[cfg.lfp_path]]

    if not cfg.params[cfg.cal_path]:
        # open selection window (at current lfp file directory) to set calibration folder path
        cfg.params[cfg.cal_path] = misc.select_file(
            cfg.params[cfg.lfp_path], 'Select calibration image')

    # cancel if file paths not provided
    sta.validate(checklist=lfp_filenames + [cfg.params[cfg.lfp_path]],
                 msg='Canceled due to missing image file path')

    # iterate through light field image(s)
    for lfp_filename in lfp_filenames:

        # change path to next filename
        cfg.params[cfg.lfp_path] = os.path.join(
            os.path.dirname(cfg.params[cfg.lfp_path]), lfp_filename)
        sta.status_msg(msg=cfg.params[cfg.lfp_path],
                       opt=cfg.params[cfg.opt_prnt])

        try:
            # decode light field image
            lfp_obj = lfp_reader.LfpReader(cfg, sta, cfg.params[cfg.lfp_path])
            lfp_obj.main()
            lfp_img = lfp_obj.lfp_img
            del lfp_obj
        except Exception as e:
            misc.PlenopticamError(e)
            continue

        # create output data folder
        misc.mkdir_p(cfg.exp_path, cfg.params[cfg.opt_prnt])

        if cfg.cond_auto_find:
            # automatic calibration data selection
            obj = lfp_calibrator.CaliFinder(cfg, sta)
            obj.main()
            wht_img = obj.wht_img
            del obj

        else:
            # manual calibration data selection
            sta.status_msg(
                '\r Please select white image calibration source manually',
                cfg.params[cfg.opt_prnt])
            # load white image calibration file
            wht_img = misc.load_img_file(cfg.params[cfg.cal_path])
            # save settings configuration
            cfg.save_params()

        # perform calibration if previously computed calibration data does not exist
        meta_cond = not (os.path.exists(cfg.params[cfg.cal_meta])
                         and cfg.params[cfg.cal_meta].lower().endswith('json'))
        if meta_cond or cfg.params[cfg.opt_cali]:
            # perform centroid calibration
            cal_obj = lfp_calibrator.LfpCalibrator(wht_img, cfg, sta)
            cal_obj.main()
            cfg = cal_obj.cfg
            del cal_obj

        # load calibration data
        cfg.load_cal_data()

        #  check if light field alignment has been done before
        if cfg.cond_lfp_align:
            # align light field
            lfp_obj = lfp_aligner.LfpAligner(lfp_img, cfg, sta, wht_img)
            lfp_obj.main()
            lfp_obj = lfp_obj.lfp_img
            del lfp_obj

        # load previously computed light field alignment
        with open(os.path.join(cfg.exp_path, 'lfp_img_align.pkl'), 'rb') as f:
            lfp_img_align = pickle.load(f)

        # export light field data
        lfp_calibrator.CaliFinder(cfg).main()
        exp_obj = lfp_extractor.LfpExtractor(lfp_img_align, cfg)
        exp_obj.main()
        del exp_obj
Ejemplo n.º 17
0
def main():

    # parse options
    cfg = parse_options(sys.argv[1:])

    # instantiate status object
    sta = misc.PlenopticamStatus()
    sta.bind_to_interrupt(sys.exit)     # set interrupt

    # set calibration folder path
    cfg.params[cfg.cal_path] = "/Users/Admin/Pictures/Lytro_Illum/CalibFolder"

    # select light field image
    cfg.params[cfg.lfp_path] = misc.select_file(cfg.params[cfg.lfp_path], 'Select plenoptic image')

    # decode light field image
    lfp_obj = lfp_reader.LfpReader(cfg, sta, cfg.params[cfg.lfp_path])
    lfp_obj.main()
    lfp_img = lfp_obj.lfp_img
    del lfp_obj

    # create output data folder
    misc.mkdir_p(cfg.params[cfg.lfp_path].split('.')[0], cfg.params[cfg.opt_prnt])

    #  check if light field alignment has been done before
    if not os.path.exists(os.path.join(cfg.params[cfg.lfp_path].split('.')[0], 'lfp_img_align.pkl')):

        # manual calibration data selection
        sta.status_msg('\r Please select white image calibration source manually', cfg.params[cfg.opt_prnt])

        # open selection window (at directory where current lfp file is located)
        cfg.params[cfg.cal_path] = misc.select_file(cfg.params[cfg.lfp_path])

        if os.path.isdir(cfg.params[cfg.cal_path]) or cfg.params[cfg.cal_path].endswith('.tar'):
            # automatic calibration data selection
            obj = lfp_calibrator.CaliFinder(cfg, sta)
            obj.main()
            wht_img = obj.wht_img
            del obj
        else:
            # load white image calibration file
            wht_img = misc.load_img_file(cfg.params[cfg.cal_path])

            # save settings configuration
            cfg.save_params()

        # perform calibration if previously computed calibration data does not exist
        meta_cond = not (os.path.exists(cfg.params[cfg.cal_meta]) and cfg.params[cfg.cal_meta].endswith('json'))
        if meta_cond or cfg.params[cfg.opt_cali]:

            # perform centroid calibration
            cal_obj = lfp_calibrator.LfpCalibrator(wht_img, cfg, sta)
            cal_obj.main()
            cfg = cal_obj.cfg
            del cal_obj

        # load calibration data
        cfg.load_cal_data()

        # align light field
        lfp_obj = lfp_aligner.LfpAligner(lfp_img, cfg, sta, wht_img)
        lfp_obj.main()
        lfp_obj = lfp_obj.lfp_img
        del lfp_obj

    # load previously computed light field alignment
    lfp_img_align = pickle.load(open(os.path.join(cfg.params[cfg.lfp_path].split('.')[0], 'lfp_img_align.pkl'), 'rb'))

    # export light field data
    exp_obj = lfp_extractor.LfpExtractor(lfp_img_align, cfg)
    exp_obj.main()
    del exp_obj
Ejemplo n.º 18
0
    crop_opt = False

    score_series = list()
    for i, target_folder in enumerate(target_folders):
        fp = os.path.join(path, target_folder)

        files = [f for f in os.listdir(fp) if f.endswith(exts)]
        files.sort()

        scores = list()
        for file in files:

            # skip file if missing
            if os.path.splitext(file)[0].split('_')[0] not in skip_list:

                img = load_img_file(os.path.join(fp, file))

                # extract image tile
                if crop_opt:
                    img = img[2:-2, 2:-2,
                              ...] if file.endswith('Thumb.png') else img
                    cy, cx = [x // 2 for x in img.shape[:2]]
                    hh, hw = [x // 10 for x in img.shape[:2]]
                    img_tile = img[cy - hh:cy + hh + 1, cx - hw:cx + hw + 1]
                else:
                    img_tile = img

                score = brisque_metric(Normalizer(img_tile).uint8_norm())
                scores.append(score)
                print(file + ': %s' % scores[-1])
Ejemplo n.º 19
0
import numpy as np
from plenopticam.misc import load_img_file


def psnr(img1=None, img2=None, quant_steps=2**8 - 1):

    img1 = np.asarray(img1, dtype=np.float64) / img1.max()
    img2 = np.asarray(img2, dtype=np.float64) / img2.max()

    mse = np.mean((img1 - img2)**2)
    if mse == 0:
        return 100
    return 20 * np.log10(quant_steps / np.sqrt(mse))


if __name__ == "__main__":

    img_ref = load_img_file(
        '/Users/Admin/Unterlagen/PhD/07 publications/18_plenopticam/IEEEtran_1st-revision/img/vign/build-sigd0.png'
    )
    img_div = load_img_file(
        '/Users/Admin/Unterlagen/PhD/07 publications/18_plenopticam/IEEEtran_1st-revision/img/vign/build-div-sigd15.png'
    )
    img_fit = load_img_file(
        '/Users/Admin/Unterlagen/PhD/07 publications/18_plenopticam/IEEEtran_1st-revision/img/vign/build-fit-sigd15.png'
    )

    print(psnr(img_ref, img_div))
    print(psnr(img_ref, img_fit))
Ejemplo n.º 20
0
# Text rendering with LaTeX
from matplotlib import rc
rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
rc('text', usetex=True)
# for Palatino
# rc('font',**{'family':'serif','serif':['Palatino']})

# plenopticam objects
cfg = PlenopticamConfig()
sta = PlenopticamStatus()

# file settings
fname = './c'
cfg.params[cfg.cal_path] = fname + '.png'
cfg.params[cfg.cal_meth] = constants.CALI_METH[2]  #'peak'   #
wht_img = load_img_file(cfg.params[cfg.cal_path])
crop = True

# load ground truth (remove outlying centers)
spots_grnd_trth = np.loadtxt(fname + '.txt')
spots_grnd_trth = spots_grnd_trth[spots_grnd_trth[:, 1] > 0]
spots_grnd_trth = spots_grnd_trth[spots_grnd_trth[:, 0] > 0]
spots_grnd_trth = spots_grnd_trth[spots_grnd_trth[:, 1] < wht_img.shape[1]]
spots_grnd_trth = spots_grnd_trth[spots_grnd_trth[:, 0] < wht_img.shape[0]]

# ensure white image is monochromatic
if len(wht_img.shape) == 3:
    wht_img = rgb2gry(wht_img)[..., 0] if wht_img.shape[-1] == 3 else wht_img

# estimate micro image diameter
obj = PitchEstimator(wht_img, cfg, sta)
Ejemplo n.º 21
0
    elif platform.system() == 'Darwin':
        fp_lytro = '/Volumes/SD CARD 1/IEEEtran/img/refo_lytro'
        fp_ours = '/Volumes/SD CARD 1/IEEEtran/img/refo_upscale_7px'
    else:
        fp_lytro = ''
        fp_ours = ''

    # loop over directories
    for fp in [fp_lytro, fp_ours]:
        slice_fns = [f for f in os.listdir(fp) if f.__contains__('crop')]

        s_list = list()

        # loop over filenames in directory
        for slice_fn in slice_fns:

            # load cropped slice
            img_tile = misc.load_img_file(os.path.join(fp, slice_fn))

            # remove alpha channel if present
            img_tile = img_tile[..., :3]

            # rescale tile for fair comparison
            img_tile = misc.img_resize(img_tile, 2.28122448) if fp.__contains__('refo_lytro') else img_tile

            # store results
            s_list.append((slice_fn, blur_metric(img_tile), michelson_contrast(img_tile)))

        for s in s_list:
            print(s)