对输入图像设置阈值

2024-04-25 01:41:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个基本的阈值程序来检查像素值是否大于阈值。(在我的例子中,我将阈值设置为128)如果它大于128,我想将该像素值设置为128,否则我将其设置为0。我有一个问题,试图让这个逻辑下来。我收到一条错误消息索引器错误:标量变量的索引无效。哪里出错了?你知道吗

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

Tags: inimportimgforthresholdas错误np
1条回答
网友
1楼 · 发布于 2024-04-25 01:41:30

问题是您试图索引一个numpy.uint8(8位无符号整数),它不是numpy数组。只要在代码中加入一些print语句,就很容易找到bug。我就是这么做的。你知道吗

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

相关问题 更多 >