我正在尝试创建一个基本的阈值程序,它检查像素值是否为>门槛。 (在我的情况下,我将阈值设置为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)
问题在于您尝试索引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()