Spaces:
Running
Running
| from PIL import Image | |
| import numpy as np | |
| import requests | |
| from io import BytesIO | |
| def resize_image(input_image: Image, resolution: int): | |
| input_image = input_image.convert("RGB") | |
| W, H = input_image.size | |
| k = float(resolution) / min(H, W) | |
| H *= k | |
| W *= k | |
| H = int(round(H / 64.0)) * 64 | |
| W = int(round(W / 64.0)) * 64 | |
| img = input_image.resize((W, H), resample=Image.LANCZOS) | |
| return img | |
| def load_image(url): | |
| # Mimic a browser request | |
| headers = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" | |
| } | |
| response = requests.get(url, headers=headers) | |
| img = Image.open(BytesIO(response.content)) | |
| return img | |
| def generate_image_from_grid(grid: np.array, img_size: int = 512) -> Image: | |
| """Generate an iamge from a grid of 0s and 1s""" | |
| n = len(grid) | |
| cell_pixel_size = img_size // n | |
| # Create a new image with white background | |
| img = Image.new("RGB", (img_size, img_size), "white") | |
| pixels = img.load() | |
| for i in range(n): | |
| for j in range(n): | |
| # Color a cell black if 0 or white if 1 | |
| color = (0, 0, 0) if grid[i][j] == 0 else (255, 255, 255) | |
| for x in range(cell_pixel_size): | |
| for y in range(cell_pixel_size): | |
| pixels[j * cell_pixel_size + x, i * cell_pixel_size + y] = color | |
| return img | |