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



我创建了一个图像字典,其中包含具有正确 x 和 y 坐标的对象。但是,此字典是线性的。假设对于 465x1000 的图像,它上升到464999键(起始索引 0(。所以当前的访问权限,假设在关键197376是这样访问

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

输出是

197376
x: 394 
y: 376

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

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

有没有办法将其转换为格式,以便可以将其作为普通列表列表进行寻址

Grids[394][376]

在指定的坐标处给出对象。

也欢迎任何其他逻辑/变体来实现这一目标。

您可以从像素坐标中反向生成索引。西普利化:

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]

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

最新更新