A comprehensive collection of algorithms and routines for electron microscopy data analysis and simulation.
—
CLI utilities for common electron microscopy data tasks including file format conversion and batch processing operations. These tools provide convenient command-line access to ncempy functionality for automated workflows and batch processing.
Command-line utility for converting various electron microscopy file formats to PNG images with proper scaling and metadata preservation.
def main():
"""
Main entry point for ncem2png command-line tool.
Command-line usage:
ncem2png input_file [options]
Options:
--output, -o: Output directory (default: current directory)
--scale: Scaling method ('linear', 'log', 'sqrt')
--colormap: Matplotlib colormap name
--dpi: Output DPI (default: 150)
--format: Output format ('png', 'jpg', 'tiff')
Returns:
int: Exit code (0 for success)
"""
def dm_to_png(dm_file, output_path, **kwargs):
"""
Convert Digital Micrograph files to PNG format.
Parameters:
- dm_file: str, path to .dm3 or .dm4 file
- output_path: str, output PNG file path
- **kwargs: conversion options (scale, colormap, dpi)
Returns:
bool: True if conversion successful
"""
def ser_to_png(ser_file, output_path, frame_index=None, **kwargs):
"""
Convert SER files to PNG format.
Parameters:
- ser_file: str, path to .ser file
- output_path: str, output PNG file path or directory
- frame_index: int, specific frame to convert (None for all frames)
- **kwargs: conversion options (scale, colormap, dpi)
Returns:
bool: True if conversion successful
"""
def _discover_emi(ser_file):
"""
Discover associated EMI metadata file for SER file.
Parameters:
- ser_file: str, path to SER file
Returns:
str or None: Path to EMI file if found
"""
def extract_dimension(data_dict, dimension_index=0):
"""
Extract dimension information from data dictionary.
Parameters:
- data_dict: dict, data structure from ncempy readers
- dimension_index: int, dimension index to extract
Returns:
dict: Dimension information including scale, units, origin
"""The following console scripts are installed with ncempy and available from the command line after installation:
Primary command-line tool for file format conversion.
# Convert single DM file to PNG
ncem2png image.dm4 -o ./output/ --scale linear --colormap gray
# Convert SER file series to individual PNGs
ncem2png series.ser -o ./frames/ --scale log --dpi 300
# Convert with custom colormap and scaling
ncem2png diffraction.dm3 --colormap hot --scale sqrt --format png# Install ncempy to get command-line tools
pip install ncempy
# Convert a single Digital Micrograph file
ncem2png my_image.dm4
# Convert with custom output directory
ncem2png my_image.dm4 -o /path/to/output/
# Convert SER file series
ncem2png tilt_series.ser -o ./series_frames/# Convert with logarithmic scaling for diffraction patterns
ncem2png diffraction.dm4 --scale log --colormap hot
# High-resolution output for publication
ncem2png hrtem_image.dm4 --dpi 300 --format png
# Square root scaling for better contrast
ncem2png phase_image.dm4 --scale sqrt --colormap viridis#!/bin/bash
# Convert all DM files in directory
for file in *.dm4; do
echo "Converting $file..."
ncem2png "$file" -o ./converted/ --scale linear --colormap gray
done
echo "Batch conversion complete"You can also use the command-line functionality from within Python scripts:
import ncempy.command_line.ncem2png as ncem2png
import subprocess
import os
# Method 1: Use the module functions directly
success = ncem2png.dm_to_png('image.dm4', 'output.png',
scale='linear', colormap='gray', dpi=150)
if success:
print("Conversion successful")
# Method 2: Call command-line tool from Python
def batch_convert_directory(input_dir, output_dir):
"""Convert all microscopy files in directory"""
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(input_dir):
if filename.endswith(('.dm3', '.dm4', '.ser')):
input_path = os.path.join(input_dir, filename)
# Call ncem2png command-line tool
cmd = ['ncem2png', input_path, '-o', output_dir,
'--scale', 'linear', '--colormap', 'gray']
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print(f"✓ Converted {filename}")
else:
print(f"✗ Failed to convert {filename}: {result.stderr}")
# Convert entire directory
batch_convert_directory('./microscopy_data/', './png_output/')import ncempy.command_line.ncem2png as ncem2png
import ncempy.io as io
import numpy as np
def convert_with_metadata_overlay(input_file, output_file):
"""Convert file and overlay metadata as text"""
# First convert to PNG
success = ncem2png.dm_to_png(input_file, output_file,
scale='linear', colormap='gray')
if success:
# Load original data to get metadata
data = io.read(input_file)
# Add metadata text overlay using PIL
from PIL import Image, ImageDraw, ImageFont
img = Image.open(output_file)
draw = ImageDraw.Draw(img)
# Create metadata text
metadata_text = f"Pixel Size: {data['pixelSize']} {data['pixelUnit']}\n"
metadata_text += f"Dimensions: {data['data'].shape}"
# Draw text on image
draw.text((10, 10), metadata_text, fill='white')
img.save(output_file)
print(f"Conversion with metadata overlay complete: {output_file}")
# Convert with metadata overlay
convert_with_metadata_overlay('sample.dm4', 'sample_with_metadata.png')ncem2png --helpUsage: ncem2png input_file [OPTIONS]
Options:
-o, --output DIR: Output directory (default: current directory)--scale {linear,log,sqrt}: Intensity scaling method (default: linear)--colormap NAME: Matplotlib colormap name (default: gray)--dpi INTEGER: Output resolution in DPI (default: 150)--format {png,jpg,tiff}: Output image format (default: png)--frame INTEGER: For series files, convert specific frame only--help: Show help message and exitSupported Input Formats:
.dm3, .dm4).ser) - converts all frames or specific frame.emd).mrc)Examples:
# Basic conversion
ncem2png image.dm4
# Custom output and scaling
ncem2png data.ser -o ./output --scale log --colormap hot
# High-resolution conversion
ncem2png sample.dm3 --dpi 300 --format png
# Convert specific frame from series
ncem2png series.ser --frame 10 -o frame_10.png# Use with ImageMagick for further processing
ncem2png image.dm4 -o temp.png && convert temp.png -resize 50% small.png
# Use with GNU parallel for high-performance batch processing
ls *.dm4 | parallel ncem2png {} -o ./converted/
# Integration with find for recursive processing
find ./data -name "*.dm4" -exec ncem2png {} -o ./png_output/ \;This command-line interface provides efficient access to ncempy's file conversion capabilities for automated workflows and batch processing of electron microscopy data.
Install with Tessl CLI
npx tessl i tessl/pypi-ncempy