地址包含 x 和 y { (x,y) 坐标 } 值作为矩阵的对象的扁平化字典

Address Flattened Dictionary of objects which contain x and y { (x,y) coordinates } values as a matrix

我创建了一个图像字典,其中包含具有正确 x 和 y 坐标的对象。然而,这本字典是线性的。假设对于一个 465x1000 的图像,它会达到 464999 的键(起始索引 0)。 所以当前的访问让我们说在密钥 197376 是这样访问的

for keys, values in Grids.items():
    print(keys)
    print(values)

输出为

197376
x: 394 
y: 376

第一个值是关键 and x : [value] and y: [value] 是对象的字符串表示形式。

如何将这个扁平的对象字典(具有这些 x 和 y 坐标)作为矩阵来处理?

有什么方法可以将其转换为一种格式,以便可以将其作为普通列表列表进行寻址

Grids[394][376]

给出指定坐标处的对象。

也欢迎实现此目标的任何其他逻辑/变体。

您可以 reverse-engenier 来自像素坐标的索引。简化:

width = 10  # max in x
height= 5   # max in y

# create linear dict with demodata list of the coords, your value would be your data object
dic = { a+b*width:[a,b] for a in range(width) for b in range(height)}

# control
print(dic)

# calculate the linear indes into dict by a given tuple of coords and the dict with data
def getValue(tup,d):
    idx = tup[0]+tup[1]*width
    return d[idx]

print(getValue((8,2),dic))       # something in between
print(getValue((0,0),dic))       # 0,0 based coords. 
print(getValue((10-1,5-1),dic))  # highest coord for my example

输出:

{0: [0, 0], 1: [1, 0], 2: [2, 0], 3: [3, 0], 4: [4, 0], 5: [5, 0], 
 6: [6, 0], 7: [7, 0], 8: [8, 0], 9: [9, 0], 10: [0, 1], 11: [1, 1], 
12: [2, 1], 13: [3, 1], 14: [4, 1], 15: [5, 1], 16: [6, 1], 17: [7, 1], 
18: [8, 1], 19: [9, 1], 20: [0, 2], 21: [1, 2], 22: [2, 2], 23: [3, 2], 
24: [4, 2], 25: [5, 2], 26: [6, 2], 27: [7, 2], 28: [8, 2], 29: [9, 2], 
30: [0, 3], 31: [1, 3], 32: [2, 3], 33: [3, 3], 34: [4, 3], 35: [5, 3], 
36: [6, 3], 37: [7, 3], 38: [8, 3], 39: [9, 3], 40: [0, 4], 41: [1, 4], 
42: [2, 4], 43: [3, 4], 44: [4, 4], 45: [5, 4], 46: [6, 4], 47: [7, 4], 
48: [8, 4], 49: [9, 4]}

[8, 2] 
[0, 0]
[9, 4]

首先使用 pandas 或 numpy 数组可能会更聪明 :o) 我对这些没有太多经验。计算线性指数是花生计算明智的,所以你也可以把它封装起来。