Search code examples
python-3.xlistdictionaryimage-processingcoordinate-systems

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


I have created a dictionary of an image with objects that have the correct x and y coordinates. However this dictionary is linear. Let's say for a 465x1000 image it goes upto keys of 464999 (starting index 0). So the current access let's say at key 197376 is accessed like this

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

And output is

197376
x: 394 
y: 376

The first values is the key and x : [value] and y: [value] is the string representation of objects.

How can I address this flattened dictionary of objects (which have these x and y coordinates) as a matrix?

Is there some way to convert it to a format so that it can be addressed as a normal list of lists

Grids[394][376]

which gives the object at the specified coordinate.

Any other logic/ variations are also welcomed which achieve this goal.


Solution

  • You can reverse-engenier the index from your pixelcoords. 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
    

    Output:

    {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]
    

    Using a pandas or numpy array in the first place would probably be smarter though :o) I do not have much experience with those. Calculating the linear index is peanuts computation wise so you can capsule that away as well.