我正在阅读这样的图像:
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/