def height2image(height): """ Converts a dictionary of heights (or brightnesses) on a grid to an image. Args: height (dict): A dictionary in which keys are coordinates for points on a grid, and the values are positive numbers of any type. Returns: image (Image): Monochrome image for which the given height dictionary determines the brightness of each pixel. The maximum value in the height dictionary is always white. """ Lx, Ly = _get_size(height) h_max = max(height.values()) image = newimage('L', (Lx, Ly)) for x in range(Lx): for y in range(Ly): if (x, y) in height: h = float(height[x, y]) / h_max else: h = 0 image.putpixel((x, y), int(255 * h)) return image
def row_swap_images(image0, image1, fraction, log=False): """ A variant of `swap_images` in which the swap process is done on each line of the images individually, rather than with the images as a whole. This makes it much faster. Args: image0, image1 (Image): RGB encoded images. fraction (float): Fraction of swap gates to apply. log (bool): If given, a logarithmic decoding is used. Returns: new_image0, new_image1 (Image): RGB encoded images. """ images = [image0, image1] Lx, Ly = images[0].size # create separate images for each row rows = [[], []] for j in range(2): for y in range(Ly): rows[j].append(newimage('RGB', (Lx, 1))) for x in range(Lx): rows[j][y].putpixel((x, 0), images[j].getpixel((x, y))) # do the swap on the row images for y in range(Ly): rows[0][y], rows[1][y] = swap_images(rows[0][y], rows[1][y], fraction, log=log) # reconstruct the full images new_images = [newimage('RGB', (Lx, Ly)) for _ in range(2)] for j in range(2): for y in range(Ly): for x in range(Lx): new_images[j].putpixel((x, y), rows[j][y].getpixel((x, 0))) return new_images[0], new_images[1]
def _heights2image(heights): """ Constructs an image from a set of three height dictionaries, one for each colour channel. """ Lx, Ly = _get_size(heights[0]) h_max = [max(height.values()) for height in heights] image = newimage('RGB', (Lx, Ly)) for x in range(Lx): for y in range(Ly): rgb = [] for j, height in enumerate(heights): if (x, y) in height: h = float(height[x, y]) / h_max[j] else: h = 0 rgb.append(int(255 * h)) image.putpixel((x, y), tuple(rgb)) return image