2017-03-12 94 views
0

我想創建一個基本的閾值程序,它檢查像素值是否>閾值。 (在我的情況下,我設置閾值爲128),如果它大於128我想將該像素值設置爲128否則我將它設置爲0.我有一個問題試圖讓這個邏輯關閉。我收到一條錯誤消息IndexError:對標量變量無效的索引。我哪裏錯了?閾值輸入圖像

import pylab as plt 
import matplotlib.image as mpimg 
import numpy as np 

    img = np.uint8(mpimg.imread('abby.jpg')) 


img = np.uint8((0.2126* img[:,:,0]) + \ 
     np.uint8(0.7152 * img[:,:,1]) +\ 
     np.uint8(0.0722 * img[:,:,2])) 



threshold = 128 

for row in img: 
    for col in row: 
    if col[0] > threshold: 
     col[0] = threshold 
    else: 
      col[0] = 0 


plt.xlim(0, 255) 
plt.hist(img,10) 
plt.show() 
+0

你可以顯示回溯?也就是說,源代碼中的哪一行代碼會導致錯誤。此外,您在嵌套循環中的縮進關閉。 –

+0

嘿,因爲在我這樣做的時候,我在複製和粘貼代碼時看起來不同步。這裏是回溯Traceback(最近調用最後一次): 文件「/Users/Micheal/PycharmProjects/untitled1/input.py」,第23行,在 如果col [0]>閾值: IndexError:對標量無效的索引變量。 –

回答

0

的問題是,你要索引numpy.uint8(8位無符號整數),這是不是一個numpy陣列。只需在代碼中添加一些打印語句,您就可以輕鬆找到該錯誤。這就是我所做的。

In [24]: for row in img: 
    ...:  # print(row) 
    ...:  for col in row: 
    ...:   print(type(col)) 
    ...:   break 
    ...:  break 
    ...: 
<class 'numpy.uint8'> 

只要改變col[0]col。另外,我通常使用plt.imshow(x)將2d numpy數組繪製爲圖像。

import pylab as plt 
import matplotlib.image as mpimg 
import numpy as np 

img = np.uint8(mpimg.imread("test.png")) 

img = np.uint8((0.2126* img[:,:,0]) + \ 
    np.uint8(0.7152 * img[:,:,1]) +\ 
    np.uint8(0.0722 * img[:,:,2])) 

threshold = 128 

for row in img: 
    for col in row: 
     if col > threshold: 
      col = threshold 
     else: 
      col = 0 

plt.imshow(img) 
plt.show()