0

空の 100*100 配列があり、この配列内に数千のランダムな位置/座標があると想像することを意図しています。これらの座標のうち、「直線」エッジの 15 ピクセル内にいくつの座標があるかを計算する必要があります。これまでのところ、私はこのコードを持っています...

import random
import pylab
import numpy                            #all import statements
pylab.close("all")

x = [(random.randint(0,100)) for i in range(3000)]      #creating list of x coordinates
y = [(random.randint(0,100)) for j in range(3000)]      #creating list of y coordinates
array=zip(x,y)                                                  #creating an array by combining the x and y coordinates
                                #end of part 1a
counter = 0                         #start of 1b
for i in range(100):
    for j in range(100):
        if i<=15 or i>=85:
                        if array[i][j]>0:
                                counter=counter+1
        elif j<=15 or j>=85:
                        if array[i][j]>0:
                                counter=counter+1

print counter,"random locations within 15 pixels of the edges"

コードを修正するにはどうすればよいですか? 現在、「タプルインデックスが範囲外です」というエラーが表示されます。if array[i][j]>0 行を参照していることは知っていますが、何が問題なのかわかりません...

4

4 に答える 4

0

あなたは近くにいます。値のまばらなグリッドを生成しています。これらのタプルを最初にディクショナリに配置して反復処理すると、エッジ違反の離散位置のそれぞれをチェックできます。以下は実際の例です。

edge_dist = 15
sparse_grid = collections.defaultdict(int)
for x,y in zip(x,y):
    sparse_grid[(x,y)] += 1
for i,j in sparse_grid:
    if (i <= edge_dist or i >= 100-edge_dist or 
            j <= edge_dist or j >= 100-edge_dist):
        counter += sparse_grid[(i,j)]

print "%d random locations within 15 pixels of the edges" % counter
# 1579 random locations within 15 pixels of the edges

バージョンで発生しているエラーは、zip が x-by-y 値のグリッドではなく、x、y のタプルを提供しているという事実によるものです。上記の zip 呼び出しの使用方法を確認できます。

于 2013-04-09T20:05:24.723 に答える
0

カバーされたエッジ スポットをカウントするために、実際にアレイを構築する必要はありません。同じ座標を 2 回カウントしないことが心配な場合は、set で重複を削除できます。

cords = set(array)                                # set removes duplicates

counter = 0
for i, j in cords:  # or array if you want to count duplicates
    if i <= 15 or i >= 85 or j <= 15 or j >= 85:
        counter += 1

print counter, "random locations within 15 pixels of the edges"
于 2013-04-09T20:28:58.510 に答える