質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

Q&A

解決済

1回答

3895閲覧

uint32のndarrayをuint8に変換

yak_jun

総合スコア13

NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

0グッド

0クリップ

投稿2019/07/24 03:35

やったこと

入力となるuint32型のndarrayを、uint8に分割したかったので以下ようなコードを書きました。
実行すると、変数bに求めている結果が格納されます。

python3

1a = np.random.randint(100, 1000, (4, 3), dtype=np.uint32) 2b = np.frombuffer(a.tobytes(), dtype=np.uint8).reshape([4, 3, 4])

実現したいこと

もっと、スマートな書き方などあるのでしょうか?
tobytesの時点で無駄なメモリのコピーが発生していたりと、改善の余地はあるとは思っております。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

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/07/27 20:20

編集2019/08/22 11:09
hayataka2049

総合スコア30933

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yak_jun

2019/08/22 10:18

ありがとうございました。 参考になりました。
hayataka2049

2019/08/22 10:30

追記に書きましたが、やるやり方はありそうです。
hayataka2049

2019/08/22 11:08

ああ、でもなんかこの方法は問題含みかもしれません。おすすめはしません。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問