3

私はベクトル化に非常に苦労しています。数学についてまだそのように考えることができないようです。私は今これを持っています:

#!/usr/bin/env python

import numpy as np
import math

grid = np.zeros((2,2))
aList = np.arange(1,5).reshape(2,2)

i,j = np.indices((2,2))

iArray =  (i - aList[:,0:1]) 
jArray = (j - aList[:,1:2])

print np.power(np.power(iArray, 2) + np.power(jArray, 2), .5)

私のプリントアウトは次のようになります。

[[ 2.23606798  1.41421356]
 [ 4.47213595  3.60555128]]

私がやろうとしているのは、ピクセル値の 2D 配列グリッドを取得し、各ピクセルが重要なピクセルのリスト aList からどれだけ離れているかを言うことです。

# # @ 
# # #
* # *

たとえば、* (0,2) と (2,2) が重要なピクセルで、現在 @ (2,0) ピクセルにいる場合、@ ピクセルの値は次のようになります。

[(0-2)^2 + (2-0)^2]^.5 + [(2-2)^2 + (0-2)^2]^.5

すべてのグリッドはピクセル値を保持するため、距離を関連付けるために各ピクセル値のインデックスを取得する必要があります。ただし、私の Alist 配列は [x,y] 座標を保持しているため、簡単です。私は今、2 つの問題があると思います: 1. インデックスを正しく取得していません 2. aList の座標を適切にループしていません

4

2 に答える 2

3

ブロードキャストの助けを借りて、最後の例に基づくデータを使用して、これを取得します。

import numpy as np

grid = np.zeros((3, 3))
aList = np.array([[2, 0], [2, 2]])

important_rows, important_cols = aList.T
rows, cols  = np.indices(grid.shape)

dist = np.sqrt((important_rows - rows.ravel()[:, None])**2 +
               (important_cols - cols.ravel()[:, None])**2).sum(axis=-1)
dist = dist.reshape(grid.shape)

>>> dist
array([[ 4.82842712,  4.47213595,  4.82842712],
       [ 3.23606798,  2.82842712,  3.23606798],
       [ 2.        ,  2.        ,  2.        ]])

次のようにすることで、メモリ効率を高めることができます。

important_rows, important_cols = aList.T
rows, cols = np.meshgrid(np.arange(grid.shape[0]),
                         np.arange(grid.shape[1]),
                         sparse=True, indexing='ij')
dist2 = np.sqrt((rows[..., None] - important_rows)**2 +
                (cols[..., None] - important_cols)**2).sum(axis=-1)
于 2013-07-03T18:41:35.727 に答える
1

私のアプローチ:

import numpy as np

n = 3

aList = np.zeros([n,n])
distance = np.zeros([n,n])

I,J = np.indices([n,n])

aList[2,2] = 1; aList[0,2] = 1   #Importan pixels
important = np.where(aList == 1) #Where the important pixels are

for i,j in zip(I[important],J[important]):   #This part could be improved...
    distance += np.sqrt((i-I)**2+(j-J)**2)

print distance

最後の「for」は改善される可能性がありますが、重要なピクセルが数個しかない場合は、パフォーマンスが向上します...


確認中:

import matplotlib.pyplot as plt

n = 500

...

aList[249+100,349] = 1; aList[249-100,349] = 1 ;aList[249,50] = 1

...

plt.plot(I[important],J[important],'rx',markersize=20)
plt.imshow(distance.T,origin='lower',
           cmap=plt.cm.gray)
plt.show()

結果は非常に快適です。

ここに画像の説明を入力

于 2013-07-03T18:20:35.823 に答える