2016-11-06 65 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。還有一種方法可以確定這一點嗎?

+0

爲什麼你會想到'lowerthreshold> IMG [I,J]和IMG [I,J]> upperthreshold'永遠是TRUE;?這意味着'80> 100'! – Eric

回答

1

你這得太多:

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

numpy,比較適用於運營商在整個陣列的elementwise。請注意,您必須使用&而不是and到布爾值相結合,因爲Python不允許numpy超載and

+0

啊,我也看到,如果我想繼續我的方向,我必須使用「或」 – User12049279432

1

你並不需要遍歷圖像陣列的X和Y位置。使用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

相關問題