I have a numpy array that is built with coded sections. The sections come in 2x2 blocks. I have a large dictionary of what those 2x2 blocks should be replaced with. How do I replace those 2x2 codes with values in the dictionary.
info_dict = {
5: np.array([[1, 0], [1, 0]], "int"),
6: np.array([[1, 0], [0, 1]], "int"),
7: np.array([[0, 1], [1, 0]], "int"),
8: np.array([[1, 1], [0, 0]], "int"),
}
print(np.array([[5, 5, 8, 8], [5, 5, 8, 8], [6, 6, 7, 7], [6, 6, 7, 7]]))
print(np.array([[1, 0, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]]))
# before (coded)
[[5 5 8 8]
[5 5 8 8]
[6 6 7 7]
[6 6 7 7]]
# after (final matrix)
[[1 0 1 1]
[1 0 0 0]
[1 0 0 1]
[0 1 1 0]]
For reference
#5
[[1 0]
[1 0]]
#6
[[1 0]
[0 1]]
#7
[[0 1]
[1 0]]
#8
[[1 1]
[0 0]]
CodePudding user response:
One way to do it:
import numpy as np
info_dict = {
5: np.array([[1, 0], [1, 0]], "int"),
6: np.array([[1, 0], [0, 1]], "int"),
7: np.array([[0, 1], [1, 0]], "int"),
8: np.array([[1, 1], [0, 0]], "int"),
}
a = np.array([[5, 5, 8, 8], [5, 5, 8, 8], [6, 6, 7, 7], [6, 6, 7, 7]])
np.block([[info_dict[b] for b in r] for r in a[::2, ::2]])
It gives:
[[1 0 1 1]
[1 0 0 0]
[1 0 0 1]
[0 1 1 0]]
CodePudding user response:
Assuming your dictionary has a small number of integers in it, and your squares are N
to a side, you info_dict
as follows:
mapping = np.zeros((max(info_dict) 1, N, N), dtype=int)
for channel, value in info_dict.items():
mapping[channel] = value
If you can store the dictionary in this format to begin with, that's even better. Now you can use simple index with some rearrangement to get the result:
after = mapping[before[::N, ::N]].transpose(0, 2, 1, 3).reshape(before.shape)