I am working on a project that needs to take a .bdf font file and turn it into a Numpy array. I am using the code below to turn the bitmap for the font into a numpy array. It currently works, I just feel that it's nearly impossible to read but I'm not sure if there's a better way to do it.
How the current code works:
- It splits the string by line since each line of the string is a row.
- It selects the first two values from the row since the last two never seem to matter.
- Using
int()
I convert the string of hex to an integer. - Using
bin()
I turn the integer to binary. - Then I use
zfill()
because leading zeros in the binary are important. This returns a string of 1's and 0's - Then I use
list()
to break the string of binary into a list of single 1's and 0's - Then I convert that all to a numpy array with
dtype=int
The process feels really messy and it takes a millisecond which I feel like is pretty long for a (15, 9) numpy array. Any ideas for improvements would be greatly appreciated.
def hexToNumpy(hexValues, columns): return np.array( [ list(bin(int(row[0:2], 16))[2:].zfill(columns)) for row in hexValues.split("\n") ], dtype=int, ) T = """0000 0000 7F00 0800 0800 0800 0800 0800 0800 0800 0800 0800 0000 0000 0000""" hexToNumpy(T, 9)