numpy配列はbytes-likeなので、tobytes()は省略して
python
1b = np.frombuffer(a, dtype=np.uint8).reshape([4, 3, 4])
とも書けます。ただし、内部的には同じか、へたするとかえって遅くなる程度ですね。
質問文のやり方はnumpyを使うのであれば最良に近いと思います。同じメモリ領域を読み替えたりするのは難しいので、そこは諦めるのが前提になります。
追記
すみません、viewで型指定すればできそうです。ただしread-onlyになりそう。
python
1>>> import numpy as np
2>>> a = np.random.randint(100, 1000, (4, 3), dtype=np.uint32)
3>>> b = np.frombuffer(a.tobytes(), dtype=np.uint8).reshape([4, 3, 4])
4>>> b
5array([[[ 67, 1, 0, 0],
6 [148, 1, 0, 0],
7 [242, 1, 0, 0]],
8
9 [[ 55, 1, 0, 0],
10 [138, 0, 0, 0],
11 [ 80, 3, 0, 0]],
12
13 [[ 66, 1, 0, 0],
14 [ 71, 3, 0, 0],
15 [100, 0, 0, 0]],
16
17 [[ 3, 3, 0, 0],
18 [ 84, 3, 0, 0],
19 [134, 2, 0, 0]]], dtype=uint8)
20>>> b2 = a.view(np.uint8).reshape(4, 3, 4)
21>>> b2
22array([[[ 67, 1, 0, 0],
23 [148, 1, 0, 0],
24 [242, 1, 0, 0]],
25
26 [[ 55, 1, 0, 0],
27 [138, 0, 0, 0],
28 [ 80, 3, 0, 0]],
29
30 [[ 66, 1, 0, 0],
31 [ 71, 3, 0, 0],
32 [100, 0, 0, 0]],
33
34 [[ 3, 3, 0, 0],
35 [ 84, 3, 0, 0],
36 [134, 2, 0, 0]]], dtype=uint8)
37>>> (b == b2).all()
38True
39
https://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array
リファレンスにはけっこう怖い記述があるので、必ずしもいい方法ではないかもしれません。
For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/22 10:18
2019/08/22 10:30
2019/08/22 11:08