Help us understand the problem. What is going on with this article?

np.whereでドツボにハマった話

はじめに

画像処理の中でnp.whereのインデックス取り出しにおける出力が全くできなかったので
ここのサンプルコードを参考にしながら理解しました・・・
なので備忘録です!
これ読み方わかったらアハ体験できるのでは!??

np.whereの出力!!?

参考にしたサンプルコードと出力です.
今回は3階テンソル($Width \times Height \times Channels = 2 \times 3 \times 4 $)
となっています.

a_3d = np.arange(24).reshape(2, 3, 4)
print(a_3d)
# output
# [[[ 0  1  2  3]
#   [ 4  5  6  7]
#   [ 8  9 10 11]]
# 
#  [[12 13 14 15]
#   [16 17 18 19]
#   [20 21 22 23]]]

print(np.where(a_3d < 5))
# output
# (array([0, 0, 0, 0, 0]), array([0, 0, 0, 0, 1]), array([0, 1, 2, 3, 0]))

ここでnp.where(a_3d < 5)の出力を
$Width$:array([0, 0, 0, 0, 0])
$Height$:array([0, 0, 0, 0, 1])
$Channels$:array([0, 1, 2, 3, 0])
のリストだとみて
$Width$:W
$Height$:H
$Channels$:C
とおくと3階テンソルの要素にアクセスするためには

a_3d[W[0]][H[0]][C[0]] = 0 
a_3d[W[1]][H[1]][C[1]] = 1 
a_3d[W[2]][H[2]][C[2]] = 2 
a_3d[W[3]][H[3]][C[3]] = 3 
a_3d[W[4]][H[4]][C[4]] = 4 

となります.
これでやっとnp.where(a_3d < 5)の出力が読めた!

さいごに

最初は配列が返ってくるだけだったのでなんだこれ?っと思ってましたが
行,列,奥行きの形が見えてくると意味のある数値に変わりますね〜
アハ体験いいですよね〜

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした