如何使用Numpy将512x512 uint16二维数组保存为大端序二进制帧?
Got it, let's break down why changing sys.byteorder isn't fixing your issue, and how to properly write your 512x512 uint16 array as big-endian binary frames.
Why sys.byteorder Isn't Working
First off, modifying sys.byteorder doesn't actually convert the byte order of your existing data. That variable is mostly a read-only indicator of your system's native byte order—even if you set it to 'big', Python won't automatically reorder bytes in your array when you write it to a file. It's just a flag, not a magic switch for data conversion.
Solution 1: Use NumPy's Byte Order Tools (Recommended for Array Data)
If you're using NumPy (standard for handling 2D numeric arrays like yours), you can directly convert the array to big-endian before writing:
import numpy as np # Replace with your actual 512x512 uint16 array frame_array = np.random.randint(0, 65535, (512, 512), dtype=np.uint16) # Convert to big-endian: byteswap() swaps byte pairs, newbyteorder() sets the array's endian flag big_endian_frame = frame_array.byteswap().newbyteorder('>') # Write to binary file with open('big_endian_frames.bin', 'wb') as fid: fid.write(big_endian_frame.tobytes())
Solution 2: Manual Packing with struct (For Non-NumPy Data)
If you're working with plain Python lists instead of NumPy arrays, use the struct module to explicitly pack each uint16 value as big-endian:
import struct # Replace with your actual 512x512 list of lists frame_array = [[np.random.randint(0, 65535) for _ in range(512)] for _ in range(512)] with open('big_endian_frames.bin', 'wb') as fid: for row in frame_array: # Pack each row: '>H' means big-endian (>) unsigned short (H), repeated for each element packed_row = struct.pack('>' + 'H' * len(row), *row) fid.write(packed_row)
Verify the Result
To confirm you've got valid big-endian data, read it back and cross-check:
# Read and parse the binary file as big-endian with open('big_endian_frames.bin', 'rb') as fid: raw_data = fid.read() parsed_array = np.frombuffer(raw_data, dtype='>u2').reshape(512, 512) # Compare to original array (should return True if conversion worked) print(np.array_equal(frame_array, parsed_array))
This should resolve the issue where Matlab/Java were reading little-endian data—your binary frames will now be properly formatted in big-endian order.
内容的提问来源于stack exchange,提问作者runcyclexcski

