├── README.md ├── images └── obama_dice.png └── main.py /README.md: -------------------------------------------------------------------------------- 1 | # Image to dice converter 2 | 3 | ## Usage 4 | 5 | Run `main.py` in a directory with an image named `input.png`, when it is done it will output a file called `output.png`. You need to have 2 packages installed, so run `pip install pygame` and `pip install opencv-python` before. 6 | 7 | ![obama dice](images/obama_dice.png) 8 | -------------------------------------------------------------------------------- /images/obama_dice.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mazore/dice/6635dd84744c0afbd2f56a449d8dd14b8b2464d8/images/obama_dice.png -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import cv2 # pip install opencv-python 2 | import pygame as pg 3 | from math import ceil 4 | 5 | DIE_WIDTH = 25 6 | RESOLUTION_FACTOR = 2 7 | 8 | pg.init() 9 | img = cv2.imread('input.png', 0) 10 | HEIGHT, WIDTH = img.shape 11 | WIDTH *= RESOLUTION_FACTOR 12 | HEIGHT *= RESOLUTION_FACTOR 13 | DOT_RADIUS = DIE_WIDTH // 10 14 | GRID_WIDTH = WIDTH // DIE_WIDTH 15 | GRID_HEIGHT = HEIGHT // DIE_WIDTH 16 | w = pg.display.set_mode((GRID_WIDTH * DIE_WIDTH, GRID_HEIGHT * DIE_WIDTH)) 17 | 18 | DOT_CENTERS = { 19 | 1: [(0, 0)], 20 | 2: [(1, -1), (-1, 1)], 21 | 3: [(1, -1), (0, 0), (-1, 1)], 22 | 4: [(-1, -1), (1, -1), (-1, 1), (1, 1)], 23 | 5: [(-1, -1), (1, -1), (-1, 1), (1, 1), (0, 0)], 24 | 6: [(-1, -1), (1, -1), (-1, 1), (1, 1), (-1, 0), (1, 0)] 25 | } 26 | 27 | # Downscale image 28 | img = cv2.resize(img, (GRID_WIDTH, GRID_HEIGHT), interpolation=cv2.INTER_AREA) 29 | 30 | 31 | def draw_dice(): 32 | for pixel_x in range(GRID_WIDTH): 33 | for pixel_y in range(GRID_HEIGHT): 34 | brightness = img[pixel_y][pixel_x] 35 | 36 | die_number = ceil(brightness / 42.5) # Map to 1-6 37 | 38 | if die_number == 0: 39 | continue 40 | 41 | die_x = pixel_x*DIE_WIDTH + 0.5*DIE_WIDTH 42 | die_y = pixel_y*DIE_WIDTH + 0.5*DIE_WIDTH 43 | 44 | for dotCenter in DOT_CENTERS[die_number]: 45 | dot_x = die_x + dotCenter[0]*DIE_WIDTH*0.25 46 | dot_y = die_y + dotCenter[1]*DIE_WIDTH*0.25 47 | pg.draw.circle(w, [255, 255, 255], (int(dot_x), int(dot_y)), DOT_RADIUS) 48 | 49 | 50 | def draw_lines(): 51 | for i in range(GRID_WIDTH): 52 | x = i * DIE_WIDTH 53 | pg.draw.line(w, [50, 50, 50], (x, 0), (x, HEIGHT)) 54 | 55 | for i in range(GRID_HEIGHT): 56 | y = i * DIE_WIDTH 57 | pg.draw.line(w, [50, 50, 50], (0, y), (WIDTH, y)) 58 | 59 | 60 | if __name__ == '__main__': 61 | draw_dice() 62 | draw_lines() 63 | pg.display.update() 64 | pg.image.save(w, "output.png") 65 | pg.quit() 66 | --------------------------------------------------------------------------------