Skip to content

Instantly share code, notes, and snippets.

@spider-man-tm
Created May 30, 2020 16:19
Show Gist options
  • Save spider-man-tm/7ca305490e0846c0c4c99923252b9e34 to your computer and use it in GitHub Desktop.
Save spider-man-tm/7ca305490e0846c0c4c99923252b9e34 to your computer and use it in GitHub Desktop.
ある画像をいくつかのブロックに分割し、ランダムに並び替えたい時
import numpy as np
import matplotlib.pyplot as plt
import cv2
import random
img = cv2.imread('img.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
def concat_tile(im_list_2d):
return cv2.vconcat([cv2.hconcat(im_list_h) for im_list_h in im_list_2d])
def tile_flip(tile):
"""
random flip
"""
tmp = np.random.randint(4)
if tmp==0:
return tile
elif tmp==1:
return tile[::-1, :, :]
elif tmp==2:
return tile[:, ::-1, :]
else:
return tile[::-1, ::-1, :]
def tile_shuffle(img, num=2):
"""
img: input image
N: number of blocks
"""
H, W, _ = img.shape
imgs = [[] for _ in range(num)]
row = 0
for i in random.sample(list(range(num)), num):
for j in random.sample(list(range(num)), num):
h = i*(H//num)
w = j*(W//num)
tmp = img[h : h+H//num, w : w+H//num, :]
tmp = tile_flip(tmp)
imgs[row].append(tmp)
row += 1
shuffle = concat_tile(imgs)
return shuffle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment