Skip to content

Instantly share code, notes, and snippets.

@otmb
Last active May 30, 2018 07:48
Show Gist options
  • Save otmb/ecfa0ac73658c4031193319c9691602d to your computer and use it in GitHub Desktop.
Save otmb/ecfa0ac73658c4031193319c9691602d to your computer and use it in GitHub Desktop.
How to handle ArrayBinary(Float)

Python blob Write

data = np.array([1.0, 2.0, 3.0, 4.0],dtype=np.float32)
with open("[filename]", "wb") as f:
    byte = np.array(data,dtype=np.float32).tobytes()
    f.write(byte)

Python blob Read

byte = open('[filename]','rb').read()
fmt = str (int (len(byte) / struct.calcsize('f'))) + 'f'
data = struct.unpack(fmt, byte) 

TypeScript blob Read at Tensor

heatmapScores = await getTensor("http://example.com/test.bin",[33,33,17]);

async function getTensor(url: String, shape:number[]): tf.Tensor3D {
  try {
    const response = await fetch(url);
    const data = await response.arrayBuffer();
    const values = await new Float32Array(data);
    const tensor = tf.Tensor.make(shape, {values});
  } catch (e) {
    console.error(e)
  }
  return tensor;
}

Swift blob Read

func getFloat(_ name: String) -> [Float] {
    let url = Bundle.main.url(forResource: name, withExtension: "bin")!
    let binaryData = try! Data(contentsOf: url, options: [])
    let values: [Float] = binaryData.withUnsafeBytes {
        [Float](UnsafeBufferPointer(start: $0, count: binaryData.count/MemoryLayout<Float32>.stride))
    }
    return values
}

Unity blob Read

TextAsset binary = Resources.Load (name) as TextAsset;
var floatValues = GetByteToFloat(binary.bytes);
        
public static float[] GetByteToFloat(byte[] byteArray) {
	var floatArray = new float[byteArray.Length / 4];
	Buffer.BlockCopy(byteArray, 0, floatArray, 0, byteArray.Length);
	return floatArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment