简体   繁体   English

阈值输入图像

[英]Thresholding an Input image

I am trying to create a basic thresholding program which checks to see if the pixel value is > the threshold. 我正在尝试创建一个基本的阈值程序,该程序检查像素值是否大于阈值。 (In my case i set the threshold as 128) if it is greater than 128 I want to set that pixel value as 128 else i set it to 0. I am having an issue trying to get this logic down. (在我的情况下,我将阈值设置为128),如果该阈值大于128,我想将该像素值设置为128,否则将其设置为0。 I get an error message IndexError: invalid index to scalar variable. 我收到一条错误消息IndexError:标量变量的索引无效。 Where am i going wrong? 我要去哪里错了?

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()

The problem is that you're trying to index a numpy.uint8 (8 bit unsigned integer), which is not a numpy array. 问题是您正在尝试索引numpy.uint8 (8位无符号整数),它不是numpy数组。 Just throw some print statements in your code and you'll easily find the bug. 只需在代码中添加一些打印语句,即可轻松找到该错误。 Here's what I did. 这就是我所做的。

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

Just change col[0] to col . 只需将col[0]更改为col Also, I usually use plt.imshow(x) to plot 2d numpy arrays as images. 另外,我通常使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM