gpt4 book ai didi

python - 使用 PIL 和 OpenCV 2 在 Python 中轴越界错误

转载 作者:行者123 更新时间:2023-12-01 01:36:55 24 4
gpt4 key购买 nike

如果图像中的所有像素处于某个阈值(如果值在 50 到 150 之间,则更改它),我想将图像中的所有像素更改为灰色 (r = g = b = 128)。我导入了图像,当我尝试处理图像时,出现以下错误:IndexError:索引 3474 超出尺寸为 3474 的轴 0 的范围(图像为 3474x4632)。

代码如下:

from PIL import Image
import numpy as np

image = Image.open("texture.jpg")
w, h = image.size
print ("%d %d" % (w, h)) #to be sure what the width and height are
im = np.array(image)
for x in range(0, w):
for y in range(0, h):
if (im[x][y][0] <= 150 and im[x][y][0] >= 50):
im[x][y][0] = 128
im[x][y][1] = 128
im[x][y][2] = 128

cv2.imwrite("image2.jpg", im)

这是我要转换的图像:https://ibb.co/hnjq4p (太大,无法在此处上传)。关于为什么它不起作用的任何想法?

最佳答案

我相信 numpy 颠倒了 PIL 的轴顺序。实际上第一个索引是行。因此,您应该循环遍历 w,h = im.shapeh,w = image.size 。也许您可以通过比较 image.sizeim.shape 来验证这是否正确?

也就是说,如果不循环的话会好得多。您可以使用masking and broadcasting实现这样的for循环任务:

im[(im[...,0]<=150)&(im[...,0]>=50)] = 128 # will modify im in place 

这会快得多,尤其是在像这样的大图像上。

请注意,这仅检查图像的第一个 channel 是否在 150 到 50 之间。这就是您的 for 循环所说的内容,所以我猜这就是您想要的。

关于python - 使用 PIL 和 OpenCV 2 在 Python 中轴越界错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52317966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com