Ejemplo n.º 1
0
def save_img_file(img, file_path=None, file_type=None):

    file_path = os.getcwd() if file_path is None else file_path
    ext = os.path.splitext(file_path)[-1][1:]
    img = place_dnp(img)

    if not file_type:
        file_type = ext if ext == 'png' or ext == 'tiff' else 'tiff' if img.dtype == 'uint16' else 'png'

    # try imageio import or use png instead if import fails
    imageio, file_type = try_tiff_import(file_type)

    # compose new file path string if extension type changed
    file_path = os.path.splitext(file_path)[-2] if file_path.endswith(
        ('.tiff', '.png', '.bmp')) else file_path
    file_type = 'png' if file_type is None else file_type
    file_path += '.' + file_type

    if file_type == 'tiff':
        imageio.imwrite(uri=file_path, im=Normalizer(img).uint16_norm())

    elif file_type == 'png' or file_type == 'bmp':
        Image.fromarray(Normalizer(img).uint8_norm()).save(file_path,
                                                           file_type,
                                                           optimize=True)

    return True
Ejemplo n.º 2
0
def save_img_file(img, file_path, file_type=None):

    img = place_dnp(img)
    ext = os.path.splitext(file_path)[-1][1:]

    if not file_type:
        file_type = ext if ext == 'png' or ext == 'tiff' else 'tiff' if img.dtype == 'uint16' else 'png'

    # try libtiff import or use png instead if import fails
    TIFF, file_type = try_tiff_import(file_type)

    # compose new file path string if extension type changed
    file_path = os.path.splitext(file_path)[-2] if file_path.endswith(
        ('.tiff', '.png', '.bmp')) else file_path
    file_path = file_path + '.' + file_type

    if file_type == 'tiff':
        obj = TIFF.open(file_path, mode='w')
        obj.write_image(Normalizer(img).uint16_norm(),
                        compression=None,
                        write_rgb=True)
        obj.close()

    elif file_type == 'png' or file_type == 'bmp':

        Image.fromarray(Normalizer(img).uint8_norm()).save(file_path,
                                                           file_type,
                                                           optimize=True)

    return True
Ejemplo n.º 3
0
def load_img_file(file_path):

    file_type = file_path.split('.')[-1]
    img = None

    # try libtiff import or use png instead if import fails
    imageio, file_type = try_tiff_import(file_type)

    if file_type.__contains__('tif'):
        suppress_user_warning(True, category=UserWarning)
        img = imageio.imread(uri=file_path)
        suppress_user_warning(False, category=UserWarning)

    elif any(file_type in ext for ext in ('bmp', 'png', 'jpeg', 'jpg')):
        try:
            img = Image.open(file_path)
            #imageio.imread(uri=file_path, format=file_type)
        except OSError:
            # support load of truncated images
            from PIL import ImageFile
            ImageFile.LOAD_TRUNCATED_IMAGES = True
            img = Image.open(file_path)
        except AttributeError:
            raise TypeError()

    elif not any(file_type in ext
                 for ext in ('bmp', 'png', 'tiff', 'jpeg', 'jpg')):
        raise TypeError('Filetype %s not recognized' % file_type)

    # normalize (convert to numpy array)
    img = Normalizer(np.asarray(img)).type_norm()

    return img
Ejemplo n.º 4
0
def get_img_list(img_dir, vp=1):
    """ obtain list of images from provided directory path """

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

            # load image
            img = load_img_file(img_path)

            # convert to uint8 if necessary
            img = Normalizer(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.º 5
0
def save_img_file(img, file_path=None, file_type=None, gamma=None, tag=None):

    # do gamma correction
    img = img**gamma if gamma is not None else img

    file_path = os.getcwd() if file_path is None else file_path

    try:
        img = place_dnp(img) if not tag else img
    except ValueError:
        pass

    # amend write privileges of (potentially existing) config file
    if os.path.exists(file_path):
        st = os.stat(file_path)
        os.chmod(file_path, st.st_mode | 0o111)

    ext = os.path.splitext(file_path)[-1][1:]
    if not file_type:
        file_type = ext if ext == 'png' or ext == 'tiff' else 'tiff' if img.dtype == 'uint16' else 'png'

    # try imageio import or use png instead if import fails
    imageio, file_type = try_tiff_import(file_type)

    # compose new file path string if extension type changed
    file_path = os.path.splitext(file_path)[-2] if file_path.endswith(
        ('.tiff', '.png', '.bmp')) else file_path
    file_type = 'png' if file_type is None else file_type
    file_path += '.' + file_type

    if file_type.__contains__('tif'):
        suppress_user_warning(True, category=UserWarning)
        imageio.imwrite(uri=file_path, im=Normalizer(img).uint16_norm())
        suppress_user_warning(False, category=UserWarning)

    elif file_type == 'png' or file_type == 'bmp':
        try:
            #Image.fromarray(Normalizer(img).uint8_norm()).save(file_path, file_type, optimize=True)
            imageio.imwrite(uri=file_path, im=Normalizer(img).uint8_norm())
        except PermissionError as e:
            raise Exception(e)

    return True
Ejemplo n.º 6
0
def img_resize(img, x_scale=1, y_scale=None, method=None, new_shape=None):
    """ perform image interpolation based on scipy lib """

    if not y_scale:
        y_scale = x_scale

    if x_scale == 1 and y_scale == 1 and new_shape is None or x_scale <= 0 or y_scale <= 0:
        return img

    method = 'cubic' if method is None else method
    dtype = img.dtype

    if len(img.shape) == 3:
        n, m, p = img.shape
    elif len(img.shape) == 2:
        n, m, p = img.shape + (1, )
        img = img[..., np.newaxis]
    else:
        raise NotImplementedError

    # construct new 2-D shape
    y_len, x_len = (int(round(n * y_scale)), int(round(
        m * x_scale))) if x_scale != 1 or y_scale != 1 else new_shape

    # interpolate
    new_img = np.zeros([y_len, x_len, p])
    for p in range(p):
        f = interp2d(range(m), range(n), img[:, :, p], kind=method)
        new_img[:, :, p] = f(np.linspace(0, m - 1, x_len),
                             np.linspace(0, n - 1, y_len))

    # normalize to the 0-1 range
    new_img = Normalizer(new_img).type_norm(new_min=0, new_max=1)

    # remove added third axes in monochromatic image
    new_img = new_img[..., 0] if new_img.shape[-1] == 1 else new_img

    return new_img.astype(dtype)
Ejemplo n.º 7
0
def robust_awb(img, t=0.3, max_iter=1000):
    """ inspired by Jun-yan Huo et al. and http://web.stanford.edu/~sujason/ColorBalancing/Code/robustAWB.m """

    img = Normalizer(img).type_norm(new_min=0, new_max=1.0)
    ref_pixel = img[0, 0, :].copy()

    u = .01  # gain step size
    a = .8  # double step threshold
    b = .001  # convergence threshold

    gains_adj = np.array([1., 1., 1.])

    for i in range(max_iter):
        img_yuv = yuv_conv(img)
        f = (abs(img_yuv[..., 1]) + abs(img_yuv[..., 2])) / img_yuv[..., 0]
        grays = np.zeros(img_yuv.shape)
        grays[f < t] = img_yuv[f < t]
        if np.sum(f < t) == 0:
            print('No valid gray pixels found.')
            break

        u_bar = np.mean(grays[..., 1])  # estimate
        v_bar = np.mean(grays[..., 2])  # estimate

        # rgb_est = yuv_conv(np.array([100, u_bar, v_bar]), inverse=True)    # convert average gray from YUV to RGB

        # U > V: blue needs adjustment otherwise red is treated
        err, ch = (u_bar, 2) if abs(u_bar) > abs(v_bar) else (v_bar, 0)

        if abs(err) >= a:
            delta = 2 * np.sign(
                err) * u  # accelerate gain adjustment if far off
        elif abs(err) < b:  # converged when u_bar and v_bar < b
            # delta = 0
            #self.sta.status_msg('AWB convergence reached', self.cfg.params[self.cfg.opt_prnt])
            break
        else:
            delta = err * u

        # negative feedback loop
        gains_adj[ch] -= delta

        img = np.dot(img, np.diag(gains_adj))

    # take gains only if result is obtained by convergence
    gains = img[0, 0, :] / ref_pixel if i != max_iter - 1 else (1, 1, 1)

    return img, gains