我的Python代码有一些奇怪的问题。我正在将彩色图像传递给黑白图像。
我正在使用PIL处理图像,这是我的功能:
class ImageEffects():
def __init__(self, h, w, img):
self.h = h
self.w = w
self.img = img
def grayScale(self):
ret = [[(0, 0, 0) for x in range(self.h)] for y in range(self.w)]
last = []
try:
for y in range(self.h):
for x in range(self.w):
if self.inside(x, y):
pixel = self.img[x, y]
newColor = int((pixel[0] + pixel[1] + pixel[2])/3)
ret[y][x] = (newColor, newColor, newColor)
last = [x, y, self.inside(x, y), self.h, self.w]
except Exception as err:
print(err)
print(last)
return np.array(ret, dtype=np.uint8)
def inside(self, x, y):
return 0 <= x < self.w and 0 <= y < self.h
除了了解问题之外,我尝试了一些尝试。现在,我以这种方式调用它:
im = Image.open(destination) # open the image to work
matrixImg = im.load()
h, w = im.size # size images
newEffects = ImageEffects(h, w, matrixImg)
gray = newEffects.grayScale()
new_image = Image.fromarray(gray)
destination = "/".join([target, userId, "gray_" + fileHashed])
new_image.save(destination)
尝试使用此图像:(https://i.imgur.com/XuwgsC3.jpg) 我得到了(https://i.imgur.com/4jpgrzm.png) 这是我在控制台中的异常日志:
image index out of range # first print exception in grayscale function
[1114, 1114, True, 1280, 1115] # second print exception in grayscale function
但是我不明白为什么索引超出范围。
也许我很累,看不到错误,但是您能帮我吗?非常感谢你们!
class ImageEffects():
def __init__(self, size, img):
self.size = size
self.img = img
def grayScale(self):
ret = [[(0, 0, 0) for x in range(self.size[0])] for y in range(self.size[1])]
last = []
try:
pixels = self.img.load()
for x in range(self.size[0]):
for y in range(self.size[1]):
if self.inside(x, y):
pixel = pixels[x, y]
newColor = abs(int((pixel[0] + pixel[1] + pixel[2])/3))
ret[y][x] = (newColor, newColor, newColor)
last = [x, y, self.inside(x, y), self.size]
except Exception as err:
print(last)
print(err)
return np.array(ret, dtype=np.uint8)
def inside(self, x, y):
return 0 <= x < self.size[0] and 0 <= y < self.size[1]
它起作用了,我将“ Image.open(file)”对象传递给ImageEffects类的img参数。然后,我不知道两个代码之间的最大区别是什么。