2016-05-02 11 views
2

イメージを渡すクラス(2D配列、1280x720)を作成しました。最高値を探して、反復処理するとしています:私はそれを実行したときにPython IndexError:範囲外

import bumpy as np 

class myCv: 
    def maxIntLoc(self,image): 
     intensity = image[0,0] #columns, rows 
     coordinates = (0,0) 
     for y in xrange(0,len(image)): 
      for x in xrange(0,len(image[0])): 
       if np.all(image[x,y] > intensity): 
        intensity = image[x,y] 
        coordinates = (x,y) 
     return (intensity,coordinates) 

は、しかし、私はエラーを取得する:

if np.all(image[x,y] > intensity): 
IndexError: index 720 is out of bounds for axis 0 with size 720 

私は、Pythonに新たなんだとすべてのヘルプは素晴らしいことです。

おかげで、Pythonで ショーン

+1

これは 'image [x、y]'か 'image [y、x]'でしょうか? – Selcuk

+0

イメージ全体を反復処理しているのはなぜですか?代わりにベクトル化の使用を検討しましたか? – Pouria

+0

@PouriaHadjibagheriあなたのコメントをありがとう、私は今ベクトル化を検討しています。 –

答えて

1

は、ほとんどのプログラミング言語と同様に、インデックスは0から始まります。

0719のピクセルしかアクセスできません。 len(image)len(image[0])が実際に1280年と関係なく、ピクセルを反復、他者によって対処されてきたあなたが経験しているインデックス・エラーの

2

720を返しているデバッグプリントと

チェック/ボクセルは有効ではありません画像を操作する方法。この問題は、curse of dimensionalityに直面している多次元画像で特に顕著になります。

これを行う正しい方法は、ベクター化をサポートするプログラミング言語(たとえばPython、Julia、MATLAB)でベクトル化を使用することです。この方法を使用すると、探している結果をより効率的に(しかも何千倍も速く)達成できます。ベクトル化(別名配列プログラミング)の詳細については、Click hereを参照してください。 Pythonでは、ジェネレータを使用するか、呼び出されるまで実際に結果を生成しないため、画像には適していません。または配列NumPyを使用します。ここで

は一例です:もちろん

enter image description here

をあなたがマスク処理(機能)を置くことができます:ベクトル化返し

from numpy.random import randint 
from matplotlib.pyplot import figure, imshow, title, grid, show 

def mask_img(img, thresh, replacement): 
    # Copy of the image for masking. Use of |.copy()| is essential to 
    # prevent memory mapping. 
    masked = initial_image.copy() 

    # Replacement is the value to replace anything that 
    # (in this case) is bellow the threshold. 
    masked[initial_image<thresh] = replacement # Mask using vectorisation methods. 

    return masked 

# Initial image to be masked (arbitrary example here). 
# In this example, we assign a 100 x 100 matrix of random integers 
# between 1 and 256 as our sample image. 
initial_image = randint(0, 256, [100, 100]) 
threshold = 150 # Threshold 

# Masking process. 
masked_image = mask_img(initial_image, threshold, 0) 

# Plots. 
fig = figure(figsize=[16,9]) 

fig.add_subplot(121) 
imshow(initial_image, interpolation='None', cmap='gray') 
title('Initial image') 
grid('off') 

fig.add_subplot(122) 
imshow(masked_image, interpolation='None', cmap='gray') 
title('Masked image') 
grid('off') 

show() 

により画像行列をマスキング

イメージのバッチでこれを行うためのループ。インデックスを変更して、3D、4D(例:MRI)、または5D(CATスキャンなど)の画像でも行うことができ、個々のピクセルまたはボクセルを繰り返し処理する必要はありません。

これが役に立ちます。

+0

これは素晴らしいです、ありがとう! –

+0

大歓迎です。それは、画像を分析するための人生をはるかに簡単に(そしてより速く)します。ところで、既存の変数をベクトルに変換したい場合は、 'numpy.array'を使用することができます。 – Pouria

関連する問題