Load raw file as a numpy array

Hi, I tried to solve this, but I just don’t know how to do it:
I’m currently trying to open a .raw file and then convert it into a numpy array. But I got this error:


The code lines I’m using are:

raw = st.file_uploader('Chose raw image')

if st.button('Read and format image'):
            img = np.fromfile(raw, dtype = np.uint16)

It is very close to the situation in PNG –> Bytes IO –> numpy conversion using file_uploader?, except I can’t use PIL as an intermediate.

Hi @Arenhart, welcome to the Streamlit community!

Assuming you are talking about the camera sensor RAW, this comment seems to be related:

The .raw is a sensor dump. I’m reading it using np.fromfile(path, dtype='>u2'). I then reshape it to the correct image size.

Hi @randyzwitch, thank you for your anwer!
Actually, its not camera sensor, but voxelized tomography images, but I do believe the formats should be equivalent, except for what the third axis represents (either time or depth). Actually, this is how I do it when using local files, but, while numpy should be aple to take the actual file object in place of the path, the object returned by st.file_uploader throws that error.

Now, I did find a workaround, but it requires me to load PIL, which i don’t use otherwise, and I do suspect it’s not efficient, but I tested it and it worked:

raw = st.file_uploader('Chose raw image')
x_length = st.number_input('X length', min_value=0, value=0)
y_length = st.number_input('Y length', min_value=0, value=0)
z_length = st.number_input('Z length', min_value=0, value=0)
byte_length = st.number_input('Byte length', min_value=1, value=1)
img = PIL.Image.frombytes('L', (1, byte_length\*x_length\*y_length\*z_length), raw.read())
img = np.array(img)[:,0]
img = img.view(f'uint{byte_length\*8}')
img = img.reshape(x_length, y_length, z_length)
1 Like