2017-03-13 78 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