I have an array with dimensions (4, X, Y), where the first dimension means a quadruplet (R, G, B, A). My goal is to transfer each X*Y RGBA quadrupt to floating-point X*Y values, given the corresponding dictionary.
My current code is as follows:
codeTable = { (255, 255, 255, 127): 5.5, (128, 128, 128, 255): 6.5, (0 , 0 , 0 , 0 ): 7.5, } for i in range(0, rows): for j in range(0, cols): new_data[i,j] = codeTable.get(tuple(data[:,i,j]), -9999)
Where data is an array with sizes (4, rows, cols) , and new_data has a size (rows, cols) .
The code works fine, but takes quite a while. How do I optimize this piece of code?
Here is a complete example:
import numpy codeTable = { (253, 254, 255, 127): 5.5, (128, 129, 130, 255): 6.5, (0 , 0 , 0 , 0 ): 7.5, } # test data rows = 2 cols = 2 data = numpy.array([ [[253, 0], [128, 0], [128, 0]], [[254, 0], [129, 144], [129, 0]], [[255, 0], [130, 243], [130, 5]], [[127, 0], [255, 120], [255, 5]], ]) new_data = numpy.zeros((rows,cols), numpy.float32) for i in range(0, rows): for j in range(0, cols): new_data[i,j] = codeTable.get(tuple(data[:,i,j]), -9999) # expected result for `new_data`: # array([[ 5.50000000e+00, 7.50000000e+00], # [ 6.50000000e+00, -9.99900000e+03], # [ 6.50000000e+00, -9.99900000e+03], dtype=float32)