Created
July 1, 2014 09:46
-
-
Save x-or/10bdd386e1ec6279afa6 to your computer and use it in GitHub Desktop.
Quadruple 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] | |
hsize = size/2 | |
new_state = np.zeros((size, size), np.uint16) | |
HL = int(math.log(hsize, base)) | |
r = np.zeros(hsize, int) | |
for i in range(hsize): | |
r[i] = digital_reverse(i, HL, base) | |
for i in range(hsize): | |
for j in range(hsize): | |
new_state[i, j] = state[r[i], j] | |
new_state[i+hsize, j] = state[r[i]+hsize, j] | |
new_state[i, j+hsize] = state[r[i], j+hsize] | |
new_state[i+hsize, j+hsize] = state[r[i]+hsize, j+hsize] | |
save_matrix(new_state, "brpattern-modulo2-power4-rule15-qbrp.png", modulo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment