python - 将图像中的像素值编辑为 numpy 数组

标签 python image numpy python-3.6

我正在阅读这样的图像:

img = np.array(Image.open(test_dir + image_name))

我想要做的是在数组中找到一个值较高的区域(250或更多)并将其减少10:

rows = img.shape[0]
cols = img.shape[1]
pixel = []
for x in range(0,rows):
    for y in range(0, cols):
        if x >= 122 and x <= 160 and y >= 34  and y <= 71:
            if img[x,y]>= 250:
                img[x,y] = img[x,y] -10
                pixel.append(img[x,y])

因此,我根据未更改的图像查看的区域应该是从 (122, 34) 到 (160,71) 的框,并且它应该有一些超过 250 的像素,但不知何故,当我运行此代码时,我结束了像素列表中没有任何内容

最佳答案

img 是一个 3 维数组吗?如果是这样,那么您的测试 img[x, y] >= 250 正在测试 3 个元素的数组是否大于 250。这将导致错误并导致您的脚本在此时终止。您没有说是否会发生这种情况。

如果它是一个 3 维数组,并且您想要检查所有 channel 在位置 x、y 处的值是否大于 250,那么您必须检查 np.all(img [x, y] >= 250) 而不是 img[x, y] >= 250

一般来说,您希望避免循环并使用矢量化操作来加快速度。

min_row = 122
max_row = 161
min_col = 34
max_col = 72
threshold = 250

row_slice = slice(min_row, max_row)
col_slice = slice(min_col, max_col)
roi = img[row_slice, col_slice] >= threshold
img[row_slice, col_slice][roi] -= 10

或更简洁但可读性较差,

roi = img[min_row:max_row, min_col:max_col] >= threshold
img[min_row:max_row, min_col:max_col][roi] -= 10

关于python - 将图像中的像素值编辑为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52303658/

相关文章:

python - 如何在 Django 模板中对齐文本或 url? - Python 速成类(class),元素 "Learning Log"

python - 抓取 https ://www. thenewboston.com/时出现 "SSL: certificate_verify_failed"错误

image - 在图像上使用特定大小的单元格绘制网格

python - 有没有办法在没有 scipy 其余部分的情况下安装 scipy 特殊模块?

python - 为什么无函数会慢?

python - 使用 SDK 在 Google Cloud 中设置环境变量时出错

html - Firefox 不显示图像,将乱码类名称分配给元素

java - 为什么不使用图片全名看不到图片?

python - Python 中多维矩阵(数组)的乘法

python - 如何按降序遍历 numpy 数组?