Example #1
0
def correct_outliers(img, n=2, perc=.2, sta=None):

    # status init
    sta = sta if sta is not None else misc.PlenopticamStatus()
    sta.status_msg('Hot pixel removal', True)

    for i in range(n, img.shape[0] - n):
        for j in range(n, img.shape[1] - n):
            win = img[i - n:i + n + 1, j - n:j + n + 1]

            # hot pixel detection
            num_hi = len(win[win > img[i, j] * (1 - perc)])

            # dead pixel detection
            num_lo = len(win[win < img[i, j] * (1 + perc)])

            if num_hi < win.size / 5 or num_lo < win.size / 5:
                # replace outlier by average of all directly adjacent pixels
                img[i, j] = (sum(sum(img[i - 1:i + 2, j - 1:j + 2])) -
                             img[i, j]) / 8.

            # progress update
            sta.progress((i * img.shape[1] + (j + 1)) / img.size * 100, True)

    return img
Example #2
0
def correct_luma_outliers(img, n=2, perc=.2, sta=None):

    # status init
    sta = sta if sta is not None else misc.PlenopticamStatus()
    sta.status_msg('Hot pixel removal', True)

    # luma channel conversion
    luma = misc.yuv_conv(img.copy())[..., 0]

    for i in range(n, luma.shape[0] - n):
        for j in range(n, luma.shape[1] - n):
            win = luma[i - n:i + n + 1, j - n:j + n + 1]

            # hot pixel detection
            num_hi = len(win[win > luma[i, j] * (1 - perc)])

            # dead pixel detection
            num_lo = len(win[win < luma[i, j] * (1 + perc)])

            if num_hi < win.size / 5 or num_lo < win.size / 5:
                # replace outlier by average of all directly adjacent pixels
                img[i, j, :] = (sum(sum(img[i - 1:i + 2, j - 1:j + 2, :])) -
                                img[i, j, :]) / 8.

            # progress update
            sta.progress((i * luma.shape[1] + (j + 1)) / luma.size * 100, True)

    return img
Example #3
0
    def pitch_eval(mean_pitch, patch_size, sta=None):
        ''' provide odd patch size that is safe to use '''

        sta = sta if sta is not None else misc.PlenopticamStatus()

        # ensure patch size and mean patch size are odd
        patch_size += np.mod(patch_size, 2) - 1
        mean_pitch += np.mod(mean_pitch, 2) - 1
        patch_safe = 3

        # comparison of patch size and mean size
        msg_str = None
        if patch_size < mean_pitch and patch_size > 3:
            patch_safe = patch_size
        elif patch_size > mean_pitch:
            patch_safe = mean_pitch
            msg_str = 'Patch size ({0} px) is larger than micro image size and reduced to {1} pixels.'
        elif patch_size < 3 and mean_pitch > 3:
            patch_safe = mean_pitch
            msg_str = 'Patch size ({0} px) is too small and increased to {1} pixels.'
        elif patch_size < 3 and mean_pitch < 3:
            sta.interrupt = True
            raise Exception(
                'Micro image dimensions are too small for light field computation.'
            )

        if msg_str:
            # status update
            sta.status_msg(msg_str.format(patch_size, mean_pitch), True)

        return patch_safe
Example #4
0
    def __init__(self, lfp_img, cfg=None, sta=None, wht_img=None):

        # input variables
        self.cfg = cfg
        self.sta = sta if sta is not None else misc.PlenopticamStatus()
        self._lfp_img = lfp_img
        self._wht_img = wht_img
Example #5
0
    def load_json(fp=None, sta=None):

        sta = sta if sta is not None else misc.PlenopticamStatus()

        # filename and filepath handling
        if fp is not None and os.path.splitext(fp)[-1] != '.json':
            fn = os.path.splitext(os.path.basename(fp))[0] + '.json'
            fp = os.path.join(os.path.splitext(fp)[0], fn)

        # load calibration data from json file
        try:
            with open(fp, 'r') as f:
                json_dict = json.load(f)
        except json.decoder.JSONDecodeError:
            os.remove(fp)
            sta.status_msg(
                'Calibration JSON File may be corrupted. Attempt to delete file %s'
                % fp,
                opt=True)
            raise PlenopticamError(
                'Calibration JSON File may be corrupted. Attempt to delete file %s'
                % fp)
        except IsADirectoryError:
            sta.status_msg('Provided location %s is a directory' % fp,
                           opt=True)
            raise PlenopticamError('Provided location %s is a directory' % fp)
        except FileNotFoundError:
            sta.status_msg('Provided file %s does not exist' % fp, opt=True)
            raise PlenopticamError('Provided file %s does not exist' % fp)

        return json_dict
    def __init__(self, *args, **kwargs):

        # input variables
        self._lfp_img = kwargs['lfp_img'] if 'lfp_img' in kwargs else None
        self._wht_img = kwargs['wht_img'] if 'wht_img' in kwargs else None
        self.cfg = kwargs['cfg'] if 'cfg' in kwargs else PlenopticamConfig()
        self.sta = kwargs['sta'] if 'sta' in kwargs else misc.PlenopticamStatus()

        # convert to float
        self._lfp_img = self._lfp_img.astype('float64') if self._lfp_img is not None else None
        self._wht_img = self._wht_img.astype('float64') if self._wht_img is not None else None

        if self.cfg.calibs:
            # micro lens array variables
            self._CENTROIDS = np.asarray(self.cfg.calibs[self.cfg.mic_list])
            self._LENS_Y_MAX = int(max(self._CENTROIDS[:, 2])+1)    # +1 to account for index 0
            self._LENS_X_MAX = int(max(self._CENTROIDS[:, 3])+1)    # +1 to account for index 0

            # micro image size evaluation
            self._M = self.pitch_max(self.cfg.calibs[self.cfg.mic_list])
            self._M = self.pitch_eval(self._M, self.cfg.params[self.cfg.ptc_leng], self.sta)
            self._C = self._M//2

        try:
            self._DIMS = self._lfp_img.shape if len(self._lfp_img.shape) == 3 else self._lfp_img.shape + (1,)
        except (TypeError, AttributeError):
            pass
        except IndexError:
            self.sta.status_msg('Incompatible image dimensions: Please either use KxLx3 or KxLx1 array dimensions')
            self.sta.error = True
Example #7
0
    def __init__(self, cfg=None, sta=None, *args, **kwargs):
        super(PropagatingThread, self).__init__(*args, **kwargs)

        # init
        self.cfg = cfg if cfg is not None else PlenopticamConfig()
        self.sta = sta if sta is not None else misc.PlenopticamStatus()
        self.exc = None
        self.ret = None
Example #8
0
    def __init__(self, lfp_img_align, cfg=None, sta=None):

        self._lfp_img_align = lfp_img_align
        self.cfg = cfg if cfg is not None else PlenopticamConfig()
        self.sta = sta if sta is not None else misc.PlenopticamStatus()

        # internal variable
        self._vp_img_arr = []
Example #9
0
    def __init__(self, lfp_img_align, cfg=None, sta=None):

        self._lfp_img_align = lfp_img_align
        self.cfg = cfg
        self.sta = sta if sta is not None else misc.PlenopticamStatus()

        # internal variables
        self._vp_img_arr = []
        self._refo_stack = []
Example #10
0
    def __init__(self, img=None, min=None, max=None, dtype=None, sta=None):

        self._dtype = img.dtype.__str__() if dtype is None else dtype
        self._img = np.asarray(img,
                               dtype='float64') if img is not None else None

        self._min = self._img.min() if min is None else min
        self._max = self._img.max() if max is None else max

        self.sta = sta if sta is not None else misc.PlenopticamStatus()
Example #11
0
    def __init__(self, lfp_img_align=None, cfg=None, sta=None):

        # input variables
        self._lfp_img_align = lfp_img_align
        self.cfg = cfg if cfg is not None else PlenopticamConfig()
        self.sta = sta if sta is not None else misc.PlenopticamStatus()

        # variables for viewpoint arrays
        self.vp_img_arr = []        # gamma corrected
        self.vp_img_linear = []     # linear gamma (for further processing)
Example #12
0
    def __init__(self, lfp_raw, cfg, sta=None, method='cubic'):

        # input variables
        self.lfp_raw = lfp_raw
        self.cfg = cfg
        self.sta = sta if sta is not None else misc.PlenopticamStatus()

        # internal variables
        self._method = method

        # output variable
        self._lfp_out = np.zeros(lfp_raw.shape)
Example #13
0
    def __init__(self, cfg=None, sta=None, lfp_path=None):

        # input and output variables
        self.cfg = cfg
        self.sta = sta if sta is not None else misc.PlenopticamStatus()

        # internal variables
        self._lfp_path = lfp_path.lower() if lfp_path is not None else cfg.params[cfg.lfp_path].lower()

        # output variables
        self._lfp_img = None
        self._wht_img = None
Example #14
0
    def __init__(self, img_buf, shape, cfg, sta=None):

        # input variables
        self.cfg = cfg
        self.sta = sta if sta is not None else misc.PlenopticamStatus()
        self._shape = shape
        self._img_buf = img_buf
        self._bit_pac = cfg.lfpimg['bit'] if 'bit' in cfg.lfpimg.keys() else 10

        # internal variables
        self._bay_img = None

        # output variables
        self._rgb_img = None
Example #15
0
    def __init__(self, cfg=None, sta=None, lfp_path=None):

        # input and output variables
        self.cfg = cfg
        self.sta = sta if sta is not None else misc.PlenopticamStatus()

        # internal variables
        self._lfp_path = lfp_path if lfp_path is not None else cfg.params[
            cfg.lfp_path]

        # output variables
        self._bay_img = None
        self._lfp_img = None
        self._json_dict = None

        # filename and file path from previously decoded data
        self.dp = os.path.splitext(self._lfp_path)[0]
        self.fn = os.path.basename(self.dp) + '.tiff'
        self.fp = os.path.join(self.dp, self.fn)
Example #16
0
    def __init__(self, bay_img=None, wht_img=None, cfg=None, sta=None):

        # input variables
        self.cfg = cfg if cfg is not None else PlenopticamConfig()
        self.sta = sta if sta is not None else misc.PlenopticamStatus()
        self._bay_img = bay_img.astype('float32') if isinstance(
            bay_img, np.ndarray) else None
        self._wht_img = wht_img.astype('float32') if isinstance(
            wht_img, np.ndarray) else None

        self._bit_pac = self.cfg.lfpimg[
            'bit'] if 'bit' in self.cfg.lfpimg else 10
        self._gains = self.cfg.lfpimg['awb'] if 'awb' in self.cfg.lfpimg else [
            1, 1, 1, 1
        ]
        self._bay_pat = self.cfg.lfpimg[
            'bay'] if 'bay' in self.cfg.lfpimg else None

        # output variables
        self._rgb_img = np.array([])
Example #17
0
    def __init__(self, lfp_img, cfg, sta=None, method='cubic'):

        # input variables
        self._lfp_img = lfp_img[..., np.newaxis] if len(
            lfp_img.shape) == 2 else lfp_img  # add 3rd axis for 2D image
        self.cfg = cfg
        self.sta = sta if sta is not None else misc.PlenopticamStatus()

        # internal variables
        self._METHOD = method
        self._CENTROIDS = np.asarray(self.cfg.calibs[self.cfg.mic_list])
        self._M = LfpCropper.pitch_max(self.cfg.calibs[self.cfg.mic_list])
        self._C = int((self._M - 1) / 2)
        self._LENS_Y_MAX = int(max(self._CENTROIDS[:, 2]))
        self._LENS_X_MAX = int(max(self._CENTROIDS[:, 3]))
        self._DIMS = self._lfp_img.shape if len(
            self._lfp_img.shape) == 3 else None

        # output variable
        self._lfp_out = np.zeros(lfp_img.shape)
Example #18
0
    def __init__(self, *args, **kwargs):

        # input variables
        self._lfp_img = kwargs['lfp_img'] if 'lfp_img' in kwargs else None
        self._wht_img = kwargs['wht_img'] if 'wht_img' in kwargs else None
        self.cfg = kwargs['cfg'] if 'cfg' in kwargs else PlenopticamConfig()
        self.sta = kwargs[
            'sta'] if 'sta' in kwargs else misc.PlenopticamStatus()

        # convert to float
        self._lfp_img = self._lfp_img.astype(
            'float64') if self._lfp_img is not None else None
        self._wht_img = self._wht_img.astype(
            'float64') if self._wht_img is not None else None

        # micro lens array variables
        self._CENTROIDS = np.asarray(self.cfg.calibs[self.cfg.mic_list])
        self._LENS_Y_MAX = int(max(self._CENTROIDS[:, 2]) +
                               1)  # +1 to account for index 0
        self._LENS_X_MAX = int(max(self._CENTROIDS[:, 3]) +
                               1)  # +1 to account for index 0

        # micro image size evaluation
        self._M = self.pitch_max(self.cfg.calibs[self.cfg.mic_list])
        self._M = self.pitch_eval(self._M, self.cfg.params[self.cfg.ptc_leng],
                                  self.sta)
        self._C = self._M // 2

        if self._lfp_img is not None:

            # get light field dimensions
            self._DIMS = self._lfp_img.shape

            # add 3rd axis for 2D image
            self._lfp_img = self._lfp_img[..., np.newaxis] if len(
                self._lfp_img.shape) == 2 else self._lfp_img
Example #19
0
def proc_vp_arr(fun, vp_img_arr, **kwargs):
    ''' process viewpoint images based on provided function handle and argument data '''

    sta = kwargs['sta'] if 'sta' in kwargs else misc.PlenopticamStatus()
    cfg = kwargs['cfg'] if 'cfg' in kwargs else Config()
    msg = kwargs['msg'] if 'msg' in kwargs else 'Viewpoint process'
    sta.status_msg(msg, cfg.params[cfg.opt_dbug])

    args = [
        kwargs[key] for key in kwargs.keys()
        if key not in ('cfg', 'sta', 'msg')
    ]

    for j in range(vp_img_arr.shape[0]):
        for i in range(vp_img_arr.shape[1]):
            vp_img_arr[j, i, :, :, :] = fun(vp_img_arr[j, i, :, :, :], *args)

            # progress update
            percentage = (i * vp_img_arr.shape[1] +
                          (j + 1)) / (vp_img_arr.shape[0] *
                                      vp_img_arr.shape[1] * 100)
            sta.progress(percentage, cfg.params[cfg.opt_dbug])

    return vp_img_arr
Example #20
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
Example #21
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
Example #22
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
Example #23
0
    def __init__(self, *args, **kwargs):

        # variables
        self._lfp_img = kwargs['lfp_img'] if 'lfp_img' in kwargs else None
        self._wht_img = kwargs['wht_img'] if 'wht_img' in kwargs else None
        self._lfp_img_align = kwargs[
            'lfp_img_align'] if 'lfp_img_align' in kwargs else None
        self.cfg = kwargs['cfg'] if 'cfg' in kwargs else PlenopticamConfig()
        self.sta = kwargs[
            'sta'] if 'sta' in kwargs else misc.PlenopticamStatus()
        self._M = 0
        self._C = 0
        self._flip = kwargs['flip'] if 'flip' in kwargs else False

        # convert to float
        self._lfp_img = self._lfp_img.astype(
            'float64') if self._lfp_img is not None else None
        self._wht_img = self._wht_img.astype(
            'float64') if self._wht_img is not None else None

        if self.cfg.calibs:
            # micro lens array variables
            self._CENTROIDS = np.asarray(self.cfg.calibs[self.cfg.mic_list])
            self._LENS_Y_MAX = int(max(self._CENTROIDS[:, 2]) +
                                   1)  # +1 to account for index 0
            self._LENS_X_MAX = int(max(self._CENTROIDS[:, 3]) +
                                   1)  # +1 to account for index 0

        # get pitch from aligned light field
        self._M = self.lfp_align_pitch() if hasattr(self,
                                                    '_lfp_img') else self._M

        # get mean pitch from centroids
        mean_pitch = self.centroid_avg_pitch(self._CENTROIDS) if hasattr(
            self, '_CENTROIDS') else self._M

        # evaluate mean pitch size and user pitch size
        self._Mn = self.safe_pitch_eval(
            mean_pitch=mean_pitch,
            user_pitch=int(self.cfg.params[self.cfg.ptc_leng]))

        # check if chosen micro image size too large
        if 0 < self._M < self._Mn:
            # remove existing pickle file
            fp = os.path.join(self.cfg.exp_path, 'lfp_img_align.pkl')
            os.remove(fp)
            # status update
            self.sta.status_msg(
                'Angular resolution mismatch in previous alignment. Redo process'
            )
            self.sta.error = True
        # check if micro image size in valid range
        elif self._M >= self._Mn > 0:
            self.cfg.params[self.cfg.ptc_leng] = self._Mn
        # check if micro image size not set
        elif self._M == 0:
            self._M = self._Mn
            self.cfg.params[self.cfg.ptc_leng] = self._Mn

        self._C = self._M // 2

        try:
            self._DIMS = self._lfp_img.shape if len(
                self._lfp_img.shape) == 3 else self._lfp_img.shape + (1, )
        except (TypeError, AttributeError):
            pass
        except IndexError:
            self.sta.status_msg(
                'Incompatible image dimensions: Please either use KxLx3 or KxLx1 array dimensions'
            )
            self.sta.error = True
Example #24
0
wht_img = whiteImg.squeeze().numpy()



image = Image.open(img_dir+'Default/img_channel000_position005_time000000000_z000.bmp')
whiteImg = TF.to_tensor(image)
whiteImg/=whiteImg.sum()
lfp_img = whiteImg.squeeze().numpy()


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')

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

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()

if cfg.cond_lfp_align():
    # align light field