binary_preparer.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import numpy as np
  2. import logging
  3. logger = logging.getLogger(__name__)
  4. def process_binary(path, slice_size, slice_from=None, slice_to=None, little_endian=False):
  5. logger.debug('little_endian: ' + str(little_endian))
  6. raw_file = open(path, 'rb')
  7. raw_file.seek(0, 2)
  8. raw_fileSize = raw_file.tell()
  9. raw_file.seek(0, 0)
  10. numx, numy = slice_size
  11. number_of_bytes = 4
  12. floats_per_slice = numx * numy
  13. bytes_per_slice = floats_per_slice * number_of_bytes
  14. number_of_slices = int(raw_fileSize / bytes_per_slice)
  15. '''
  16. here we can get a subset of the binary for faster testing
  17. tmpOutputFile = open('/tmp/binary_61_100_%d.raw' % time.time(), 'wb')
  18. raw_file.seek(bytes_per_slice * 61, 0)
  19. tmpOutputFile.write(raw_file.read(bytes_per_slice * 40))
  20. tmpOutputFile.close()
  21. raw_file.seek(0, 0)
  22. raise ValueError('outputfile written')
  23. '''
  24. if (slice_from is not None and
  25. slice_to is not None):
  26. number_of_slices = slice_to - slice_from + 1
  27. raw_file.seek(slice_from * bytes_per_slice, 0)
  28. floats = np.empty((1, number_of_slices * floats_per_slice), dtype=np.float32)
  29. endian_string = '>'
  30. if little_endian is True:
  31. endian_string = '<'
  32. dt = np.dtype('%s%s' % (endian_string, 'f'))
  33. floats[0] = np.fromfile(raw_file, dtype=dt)
  34. floats = (floats - floats.min()) / (floats.max() - floats.min())
  35. floats = floats.reshape((1, number_of_slices, numy, numx))
  36. return floats