Created
June 29, 2014 21:41
-
-
Save x-or/0460436a307650807b89 to your computer and use it in GitHub Desktop.
Bit/Digit-Reversal Permutation (rows only)
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 math | |
import numpy as np | |
from PIL import Image | |
np.set_printoptions(linewidth = 180, edgeitems=10, suppress = True) | |
def digital_reverse(n, length, base): | |
r = 0 | |
for _ in range(length): | |
r = base*r + n % base | |
n /= base | |
return r | |
assert digital_reverse(123, 3, 10) == 321 | |
assert digital_reverse(54321, 5, 10) == 12345 | |
assert digital_reverse(0x123, 3, 16) == 0x321 | |
assert digital_reverse(0x54321, 5, 16) == 0x12345 | |
def load_matrix_from_image(fn, modulo): | |
im = Image.open(fn) | |
pix = im.load() | |
m = np.zeros((im.size[1], im.size[0]), np.uint16) | |
gray = [255*i/(modulo-1) for i in range(modulo)] | |
rgb = [(c, c, c) for c in gray] | |
color_index = {} | |
for i in xrange(modulo): | |
color_index[gray[i]] = i | |
color_index[rgb[i]] = i | |
for y in range(im.size[1]): | |
for x in range(im.size[0]): | |
for i in xrange(modulo): | |
m[y, x] = color_index[pix[x, y]] | |
return m | |
def save_matrix(m, fn, modulo): | |
image = Image.new("L", (m.shape[1], m.shape[0]), 0) | |
pix = image.load() | |
for y in xrange(m.shape[0]): | |
for x in xrange(m.shape[1]): | |
pix[x, y] = 255*m[y, x]/(modulo-1) | |
image.save(fn, "png") | |
if __name__ == '__main__': | |
base = 2 | |
modulo = 2 | |
state = load_matrix_from_image("brpattern-modulo2-power4-rule15.png", modulo) | |
size = state.shape[0] | |
new_state = np.zeros((size, size), np.uint16) | |
L = int(math.log(size, base)) | |
r = np.zeros(size, int) | |
for i in range(size): | |
r[i] = digital_reverse(i, L, base) | |
for i in range(size): | |
for j in range(size): | |
new_state[i, j] = state[r[i], j] | |
save_matrix(new_state, "brpattern-modulo2-power4-rule15-brprows.png", modulo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment