MRC File I/O Library

1.5.4 · active · verified Tue Apr 14

mrcfile is a pure Python library designed for reading and writing MRC2014 file format data, commonly used in structural biology for image and volume data. It provides a simple API to expose file headers and data as NumPy arrays. The library is actively maintained, with frequent updates to support new Python and NumPy versions, and to enhance features like large file handling and validation.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a new MRC file with random data and then open it to inspect its header and data. It uses `mrcfile.new()` for creation and `mrcfile.open()` for reading, both utilizing Python's `with` statement for proper file handling. NumPy is used for data generation and manipulation.

import mrcfile
import numpy as np
import os

# Define a filename for the MRC file
filename = 'example.mrc'

# Create a new MRC file with some dummy data
data = np.random.rand(10, 20, 30).astype(np.float32)
with mrcfile.new(filename, data=data) as mrc:
    mrc.voxel_size = 1.5 # Set a custom voxel size
    print(f"Created {filename} with shape {mrc.data.shape} and voxel size {mrc.voxel_size}")

# Open an existing MRC file in read mode
with mrcfile.open(filename) as mrc:
    print(f"Opened {filename}. Data shape: {mrc.data.shape}, dtype: {mrc.data.dtype}")
    print(f"Header map ID: {mrc.header.map.decode('ascii')}")
    # Accessing a slice of data
    first_slice = mrc.data[0, :, :]
    print(f"First slice min/max: {first_slice.min()}/{first_slice.max()}")

# Clean up the created file
os.remove(filename)

view raw JSON →