예제 #1
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
예제 #2
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