pythonpython-3.xdata-mining

Generate image matrix from Freeman chain code


Suppose I have a 8-direction freeman chain code as follows, in a python list:

freeman_code = [3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5]

Where directions would be defined as follows:

Freeman code directions

I need to convert this to an image matrix of variable dimensions with values of 1s and 0s where 1s would depict the shape, as follows, for example:

image_matrix = [
[0, 0, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 1]
]

Of course, the above is not an exact implementation of the above freeman code. Is there any implementation in python, or in any language that achieves this? My idea (in python): Use a defaultdict of defaultdicts with 0 as default:

ImgMatrixDict = defaultdict(lambda: defaultdict(lambda:0))

and then start at a midpoint, say ImgMatrixDict[25][25], and then change values to 1 depending on the freeman code values as I traverse. After this I would convert ImgMatrixDict to a list of lists.

Is this a viable idea?

PS: On performance, yes it would not be important as I won't be doing this in real time, but generally a code would be around 15-20 characters in length. I assumed a 50*50 by matrix would suffice for this purpose.


Solution

  • If I am understanding your question correctly:

    import numpy as np 
    import matplotlib.pyplot as plt
    
    freeman_code = [3, 3, 3, 6, 6, 4, 6, 7, 7, 0, 0, 6]
    img = np.zeros((10,10))
    
    x, y = 4, 4 
    img[y][x] = 1
    for direction in freeman_code:
        if direction in [1,2,3]:
            y -= 1
        if direction in [5,6,7]:
            y += 1
        if direction in  [3,4,5]:
            x -= 1
        if direction in [0,1,7]:
            x += 1
    
        img[y][x] = 1
    
    plt.imshow(img, cmap='binary', vmin=0, vmax=1)
    plt.show()
    

    enter image description here