def postprocess_image(image: tf.Tensor, original_shape: tuple) -> np.array: """ Transforms created image from tf.Tensor to np. array. Image is resized to original size, batch dimension is removed, also VGG preprocessing is reverted. Output image is normalized to values [0, 1]. Args: image: created image as tf.Tensor original_shape: original shape of the image to resize to Returns: image: image as np.array with values in [0, 1] and size of original image """ image = image.numpy() print(f'\nPostprocessing result image from {image.shape} to {original_shape}') image = image.reshape(image.shape[1:]) # drop batch dimension # # INVERTING VGG19 PREPROCESSING # image[:, :, 0] += 103.939 # image[:, :, 1] += 116.779 # image[:, :, 2] += 123.68 # image = image[:, :, ::-1] image = tf.image.resize(image, original_shape[0:-1]).numpy() image = normalize_image(image) # normalize values to [0, 1] return image
def imwrite(img: tf.Tensor, filename: str, gamma: float = 2.2, normalize: bool = False): """ write img to filename Args ==== img: tf.Tensor filename: str gamma: float if the image is not an OpenEXR file, apply gamma correction normalize: normalize img to the range [0, 1] before writing """ directory = os.path.dirname(filename) if directory != '' and not os.path.exists(directory): os.makedirs(directory) assert (tf.executing_eagerly()) img = img.numpy() if normalize: img_rng = np.max(img) - np.min(img) if img_rng > 0: img = (img - np.min(img)) / img_rng if filename[-4:] == '.exr': if len(img.shape) == 2: img = img.reshape((img.shape[0], img.shape[1], 1)) if img.shape[2] == 1: img = np.tile(img, (1, 1, 3)) img_r = img[:, :, 0] img_g = img[:, :, 1] img_b = img[:, :, 2] pixels_r = img_r.astype(np.float16).tostring() pixels_g = img_g.astype(np.float16).tostring() pixels_b = img_b.astype(np.float16).tostring() HEADER = OpenEXR.Header(img.shape[1], img.shape[0]) half_chan = Imath.Channel(Imath.PixelType(Imath.PixelType.HALF)) HEADER['channels'] = dict([(c, half_chan) for c in "RGB"]) exr = OpenEXR.OutputFile(filename, HEADER) exr.writePixels({'R': pixels_r, 'G': pixels_g, 'B': pixels_b}) exr.close() else: skimage.io.imsave(filename, (np.power(np.clip(img, 0.0, 1.0), 1.0 / gamma) * 255).astype(np.uint8))
def tensor_to_image(tensor: tf.Tensor, width: int, height: int, channels: int = 3) -> np.array: """ Convert tensor representation of an image into displayable array :param tensor: tensor with image content :param height: target image height :param width: target image width :param channels: number of channels in an image :return: ND numpy array with image content """ tensor = tensor.reshape((height, width, channels)) # Remove zero-center by mean pixel tensor[:, :, 0] += 103.939 tensor[:, :, 1] += 116.779 tensor[:, :, 2] += 123.68 tensor = tensor[:, :, ::-1] return np.clip(tensor, 0, 255).astype('uint8')