2016-11-06 3 views
0

私の質問をお読みいただきありがとうございます。イメージ(np.array)をバイナリイメージに変換する

私はPythonには新しく、scipyに興味がありました。私はRacoonのイメージを(scipy miscで)バイナリイメージ(黒、白)にする方法を理解しようとしています。これはscipy-lectureチュートリアルでは教えられません。

これは、これまでの私のコードです:

%matplotlib inline 
import matplotlib.pyplot as plt 
import numpy as np 
from scipy import misc #here is how you get the racoon image 

face = misc.face() 
image = misc.face(gray=True) 
plt.imshow(image, cmap=plt.cm.gray) 
print image.shape 

def binary_racoon(image, lowerthreshold, upperthreshold): 
    img = image.copy() 
    shape = np.shape(img) 

    for i in range(shape[1]): 
     for j in range(shape[0]): 
      if img[i,j] < lowerthreshold and img[i,j] > upperthreshold: 
       #then assign black to the pixel 
      else: 
       #then assign white to the pixel 

    return img 

    convertedpicture = binary_racoon(image, 80, 100) 
    plt.imshow(convertedpicture, cmap=plt.cm.gist_gray) 

私は絵のバイナリを作るためのOpenCVを使用して他の人を見てきましたが、私はピクセルをループすることにより、この方法でそれを行うことができますどのように疑問に思って?私は上限値と下限値にどのような値を与えるのか分からないので、80と100の推測値を作りました。これを決定する方法はありますか?あなたがこのoverthinkingいる

+0

なぜあなたは '下しきい値> IMG [I、J]とIMG [I、J]期待>今までに' true'を可能にupperthreshold'?それは '80> 100'を意味するでしょう! – Eric

答えて

1

numpy

def to_binary(img, lower, upper): 
    return (lower < img) & (img < upper) 

を、比較演算子は、全体の配列要素ごとに適用されます。あなたはPythonがnumpyあなたは画像アレイのxとyの位置を反復処理する必要はありませんand

+0

ああ、また私は自分の方向を続けたいと思ったら "or"を使わなければならなかった – User12049279432

1

をオーバーロードすることができないので、ブール値を組み合わせること&の代わりandを使用する必要があることに注意してください。配列が関心のある閾値よりも上にあるかどうかを確認するには、numpy配列を使用します。ブール値(真偽)の配列を白黒画像として生成するコードを次に示します。

# use 4 different thresholds 
thresholds = [50,100,150,200] 

# create a 2x2 image array 
fig, ax_arr = plt.subplots(2,2) 

# iterate over the thresholds and image axes 
for ax, th in zip(ax_arr.ravel(), thresholds): 
    # bw is the black and white array with the same size and shape 
    # as the original array. the color map will interpret the 0.0 to 1.0 
    # float array as being either black or white. 
    bw = 1.0*(image > th) 
    ax.imshow(bw, cmap=plt.cm.gray) 
    ax.axis('off') 

# remove some of the extra white space 
fig.tight_layout(h_pad=-1.5, w_pad=-6.5) 

enter image description here

関連する問題