正如标题所说,我正在尝试用Python定义一个矩阵数组(代表图像)。但是,当我尝试读取矩阵时,我得到了这样的信息:“ImageData实例没有属性' getitem '”“” 我这几天开始学习Python,所以我知道这对很多人来说都很简单,但我不知道出了什么问题。这是我的代码:
import random
import math
class ImageData:
def __init__ (self, width, height):
self.width = width
self.height = height
self.data = []
for i in range(width):
self.data.append([0] * height)
def set_data (self, x, y, value):
self.data[x][y] = value
def generate_voronoi_diagram (self, seeds):
nx = []
ny = []
nr = []
ng = []
nb = []
for i in range(seeds):
# Generate a cell position
pos_x = random.randrange(self.width)
pos_y = random.randrange(self.height)
nx.append(pos_x)
ny.append(pos_y)
# Save the rgb data
nr.append(random.randrange(256))
ng.append(random.randrange(256))
nb.append(random.randrange(256))
for x in range(self.width):
for y in range(self.height):
# Return the Euclidean norm
d_min = math.hypot(self.width-1, self.height-1)
j = -1
for i in range(seeds):
# The distance from a cell to x, y point being considered
d = math.hypot(nx[i]-x, ny[i]-y)
if d < d_min:
d_min = d
j = i
self.data[x][y] = [nr[j], ng[j], nb[j]]
from PIL import Image
import numpy
import ImageData
def generate_uncertainty_visualisation (images, width, height):
image = Image.new("RGB", (width, height))
putpixel = image.putpixel
r = g = b = []
for i in range(width):
r.append([0] * height)
g.append([0] * height)
b.append([0] * height)
for i in range(len(images)):
image = images[i]
for x in range(width):
for y in range(height):
#Error here
rgb = image[x][y]
r[x][y] += rgb[0]
g[x][y] += rgb[1]
b[x][y] += rgb[2]
for x in range(width):
for y in range(height):
r[x][y] /= len(images)
g[x][y] /= len(images)
b[x][y] /= len(images)
putpixel((x, y), (r[x][y], g[x][y], b[x][y]))
image.save("output.png", "PNG")
if __name__ == "__main__":
width = 10;
height = 10;
entries = []
seeds = numpy.random.poisson(20)
images = 1
for n in range(images):
entry = ImageData.ImageData(width, height)
entry.generate_voronoi_diagram(seeds)
entries.append(entry)
generate_uncertainty_visualisation(entries, width, height)
非常感谢任何帮助。 感谢。
答案 0 :(得分:0)
首先在UncertaintyVisualisaton.py
设置:
image = Image.new("RGB", (width, height))
然后循环images
你重新分配:
image = images[i]
这可能不是你想要的。
还有你的错误:
#Error here
rgb = image[x][y]
正在发生,因为ImageData不是列表。其中的数据是:
#no more Error here
rgb = image.data[x][y]