Last active
August 6, 2019 10:56
-
-
Save anilsathyan7/e09ece1569636a44944c444344ad90a4 to your computer and use it in GitHub Desktop.
Scramble-Unscramble - Shuffles images into fixed size patches to create a jigsaw puzzle.A key-map dictionary is used to recover the shuffled image.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from PIL import Image | |
from imageio import imsave | |
from skimage.util.shape import view_as_blocks | |
# Global shuffle key | |
map={} | |
''' | |
Args:- | |
im: Image to be shuffled (square shape) | |
num: number of rows = columns | |
inverse: shuffle or inverse-shuffle | |
''' | |
def shuffle(im, num, inverse = False): | |
global map | |
rows=cols=num | |
blk_size=im.shape[0]//rows # patch size | |
# Create an array of num*num elements of size (blk_size,blk_size,3) | |
img_blks=view_as_blocks(im,block_shape=(blk_size,blk_size,3)).reshape((-1,blk_size,blk_size,3)) | |
# Initialize output array | |
img_shuff=np.zeros((im.shape[0], im.shape[0],3),dtype=np.uint8) | |
# Create a random shuffle key | |
a=np.arange(rows*rows, dtype=np.uint8) | |
b=np.random.permutation(a) | |
if(inverse): | |
inv_map = {v: k for k, v in map.items()} | |
print("Inverse Map:-\n" + str(inv_map)) | |
else: | |
map = {k:v for k,v in zip(a,b)} | |
print("Key Map:-\n" + str(map)) | |
# Shuffle the image according to key | |
for i in range(0,rows): | |
for j in range(0,cols): | |
x,y = i*blk_size, j*blk_size | |
if(inverse): | |
img_shuff[x:x+blk_size, y:y+blk_size] = img_blks[inv_map[i*rows + j]] | |
else: | |
img_shuff[x:x+blk_size, y:y+blk_size] = img_blks[map[i*rows + j]] | |
return img_shuff | |
# Input RGB image | |
im=np.array(Image.open('angrybird.jpeg').convert('RGB')) | |
shuff=shuffle(im,7, inverse=False) | |
reverted=shuffle(shuff,7, inverse=True) | |
# Output RGB images | |
imsave("scramble.png",shuff) | |
imsave("unscramble.png",reverted) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment