回答編集履歴

2

追記

2019/08/22 11:09

投稿

hayataka2049
hayataka2049

スコア30939

test CHANGED
@@ -110,8 +110,16 @@
110
110
 
111
111
 
112
112
 
113
- https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html
113
+ https://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array
114
114
 
115
115
 
116
116
 
117
- https://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array
117
+ リファレンスにはけっこう怖い記述があるので、必ずしもいい方法ではないかもしれません。
118
+
119
+
120
+
121
+ > 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.
122
+
123
+
124
+
125
+ > https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html

1

追記

2019/08/22 11:09

投稿

hayataka2049
hayataka2049

スコア30939

test CHANGED
@@ -15,3 +15,103 @@
15
15
 
16
16
 
17
17
  質問文のやり方はnumpyを使うのであれば最良に近いと思います。同じメモリ領域を読み替えたりするのは難しいので、そこは諦めるのが前提になります。
18
+
19
+
20
+
21
+
22
+
23
+ ### 追記
24
+
25
+ すみません、viewで型指定すればできそうです。ただしread-onlyになりそう。
26
+
27
+
28
+
29
+ ```python
30
+
31
+ >>> import numpy as np
32
+
33
+ >>> a = np.random.randint(100, 1000, (4, 3), dtype=np.uint32)
34
+
35
+ >>> b = np.frombuffer(a.tobytes(), dtype=np.uint8).reshape([4, 3, 4])
36
+
37
+ >>> b
38
+
39
+ array([[[ 67, 1, 0, 0],
40
+
41
+ [148, 1, 0, 0],
42
+
43
+ [242, 1, 0, 0]],
44
+
45
+
46
+
47
+ [[ 55, 1, 0, 0],
48
+
49
+ [138, 0, 0, 0],
50
+
51
+ [ 80, 3, 0, 0]],
52
+
53
+
54
+
55
+ [[ 66, 1, 0, 0],
56
+
57
+ [ 71, 3, 0, 0],
58
+
59
+ [100, 0, 0, 0]],
60
+
61
+
62
+
63
+ [[ 3, 3, 0, 0],
64
+
65
+ [ 84, 3, 0, 0],
66
+
67
+ [134, 2, 0, 0]]], dtype=uint8)
68
+
69
+ >>> b2 = a.view(np.uint8).reshape(4, 3, 4)
70
+
71
+ >>> b2
72
+
73
+ array([[[ 67, 1, 0, 0],
74
+
75
+ [148, 1, 0, 0],
76
+
77
+ [242, 1, 0, 0]],
78
+
79
+
80
+
81
+ [[ 55, 1, 0, 0],
82
+
83
+ [138, 0, 0, 0],
84
+
85
+ [ 80, 3, 0, 0]],
86
+
87
+
88
+
89
+ [[ 66, 1, 0, 0],
90
+
91
+ [ 71, 3, 0, 0],
92
+
93
+ [100, 0, 0, 0]],
94
+
95
+
96
+
97
+ [[ 3, 3, 0, 0],
98
+
99
+ [ 84, 3, 0, 0],
100
+
101
+ [134, 2, 0, 0]]], dtype=uint8)
102
+
103
+ >>> (b == b2).all()
104
+
105
+ True
106
+
107
+
108
+
109
+ ```
110
+
111
+
112
+
113
+ https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html
114
+
115
+
116
+
117
+ https://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array