我创建了一个图像字典,其中的对象具有正确的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]
给出指定坐标处的对象。
也欢迎任何其他逻辑/变体来实现这一目标。
答案 0 :(得分:1)
您可以从像素线中反转生成索引。 Siplificated:
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)我没有太多经验。计算线性指数是花生计算方式,所以你也可以把它封装起来。