2017-03-13 79 views
0

這是我的理解,thresholding是一個階梯函數意味着像素值四捨五入每一步。例如。像素值33將四捨五入爲32(假設有32的閾值)。在我的代碼中,我正在嘗試完成閾值處理,但我不認爲我正在嘗試它。有人可以指導我什麼我失蹤?如何創建圖像的閾值?

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: ## trying to loop through to find if each image pixel > threshold 
    for col in row: 
     if col > threshold: 
     col = threshold 
     else: 
     col = 0 

plt.imshow(img,cmap=plt.cm.gray) 
plt.show() 

回答

0

您沒有寫入圖像文件的閾值,而是寫入局部變量c。要讀取和寫入一個numpy數組,請閱讀官方文檔here

嘗試以下代碼: -

import pylab as plt 
import matplotlib.image as mpimg 
import numpy as np 
from PIL import Image 

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 = 64 

it = np.nditer(img, flags=['multi_index'], op_flags=['writeonly']) 
while not it.finished: 
    if it[0] > threshold: 
     it[0] = threshold 
    else: 
     it[0] = 0 
    it.iternext() 

im = Image.fromarray(img) 
im.save("output.jpeg") 
plt.imshow(img,cmap=plt.cm.gray) 
plt.show() 

輸出圖像

Output

:當心matplotlib是如何顯示所述輸出圖像的。它以純白色顯示強度64,這是不正確的表示。

+0

請閱讀K.Sarkar和我之間的簡單代碼的評論討論。感謝他在Python中的專業知識。 – saurabheights

1

檢查您的for循環。可能是因爲使用for循環迭代而犯錯誤。

if col > threshold: 
     col = threshold 

應該是255,即閾值的概念。

謝謝

+0

不一定,閾值可以用多種方式完成,設置爲255是一種方法。此外,這裏的問題是閾值被寫入局部變量而不是圖像內存。 – saurabheights

+0

對於這種情況下,只有1行代碼就足夠了:img [img

+1

是的,這會工作,但需要兩次迭代:'img [ img threshold] =閾值;'。我在Python中並不擅長,但可以通過合併兩個命令的索引篩選將它轉換爲單個迭代。 – saurabheights