2016-10-26 4 views
1

現在、私は白にすべての非黒画素に変換するには、次のコードを使用しています:Numpyでこのコードをスピードアップするには?

def convert(self, img): 
    for i in range(img.shape[0]): 
     for j in range(img.shape[1]): 
      if img.item(i, j) != 0: 
       img.itemset((i, j), 255) 
    return img 

私はそれをスピードアップすることができますどのように?

答えて

2

0ではありませんすべての要素が255に変更する必要があります。

a[a != 0] = 255 
0

方法PILを使ってについては、このように機能します

def convert (self,image): 
    return image.convert('1') 

テストコード:

from PIL import Image 
import matplotlib.pyplot as plt 

def convert (image): 
    return image.convert('1') 

img = Image.open('./test.png') 
plt.figure(); plt.imshow(img) 
BW = convert(img) 
plt.figure(); plt.imshow(BW) 
plt.show() 

結果:

enter image description here enter image description here

そして、ところで、あなたはPILの画像オブジェクトのnumpyの配列を必要とする場合には、あなたは簡単にそれを使用して取得することができます:

matrix_of_img = numpy.asarray(img.convert('L')) 
関連する問題