0
# Command Line Tools
1
2
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.
3
4
## Capabilities
5
6
### ncem2png Conversion Tool
7
8
Command-line utility for converting various electron microscopy file formats to PNG images with proper scaling and metadata preservation.
9
10
```python { .api }
11
def main():
12
"""
13
Main entry point for ncem2png command-line tool.
14
15
Command-line usage:
16
ncem2png input_file [options]
17
18
Options:
19
--output, -o: Output directory (default: current directory)
20
--scale: Scaling method ('linear', 'log', 'sqrt')
21
--colormap: Matplotlib colormap name
22
--dpi: Output DPI (default: 150)
23
--format: Output format ('png', 'jpg', 'tiff')
24
25
Returns:
26
int: Exit code (0 for success)
27
"""
28
29
def dm_to_png(dm_file, output_path, **kwargs):
30
"""
31
Convert Digital Micrograph files to PNG format.
32
33
Parameters:
34
- dm_file: str, path to .dm3 or .dm4 file
35
- output_path: str, output PNG file path
36
- **kwargs: conversion options (scale, colormap, dpi)
37
38
Returns:
39
bool: True if conversion successful
40
"""
41
42
def ser_to_png(ser_file, output_path, frame_index=None, **kwargs):
43
"""
44
Convert SER files to PNG format.
45
46
Parameters:
47
- ser_file: str, path to .ser file
48
- output_path: str, output PNG file path or directory
49
- frame_index: int, specific frame to convert (None for all frames)
50
- **kwargs: conversion options (scale, colormap, dpi)
51
52
Returns:
53
bool: True if conversion successful
54
"""
55
56
def _discover_emi(ser_file):
57
"""
58
Discover associated EMI metadata file for SER file.
59
60
Parameters:
61
- ser_file: str, path to SER file
62
63
Returns:
64
str or None: Path to EMI file if found
65
"""
66
67
def extract_dimension(data_dict, dimension_index=0):
68
"""
69
Extract dimension information from data dictionary.
70
71
Parameters:
72
- data_dict: dict, data structure from ncempy readers
73
- dimension_index: int, dimension index to extract
74
75
Returns:
76
dict: Dimension information including scale, units, origin
77
"""
78
```
79
80
## Console Script Entry Points
81
82
The following console scripts are installed with ncempy and available from the command line after installation:
83
84
### ncem2png
85
86
Primary command-line tool for file format conversion.
87
88
```bash
89
# Convert single DM file to PNG
90
ncem2png image.dm4 -o ./output/ --scale linear --colormap gray
91
92
# Convert SER file series to individual PNGs
93
ncem2png series.ser -o ./frames/ --scale log --dpi 300
94
95
# Convert with custom colormap and scaling
96
ncem2png diffraction.dm3 --colormap hot --scale sqrt --format png
97
```
98
99
## Usage Examples
100
101
### Basic File Conversion
102
103
```bash
104
# Install ncempy to get command-line tools
105
pip install ncempy
106
107
# Convert a single Digital Micrograph file
108
ncem2png my_image.dm4
109
110
# Convert with custom output directory
111
ncem2png my_image.dm4 -o /path/to/output/
112
113
# Convert SER file series
114
ncem2png tilt_series.ser -o ./series_frames/
115
```
116
117
### Advanced Conversion Options
118
119
```bash
120
# Convert with logarithmic scaling for diffraction patterns
121
ncem2png diffraction.dm4 --scale log --colormap hot
122
123
# High-resolution output for publication
124
ncem2png hrtem_image.dm4 --dpi 300 --format png
125
126
# Square root scaling for better contrast
127
ncem2png phase_image.dm4 --scale sqrt --colormap viridis
128
```
129
130
### Batch Processing with Shell Scripts
131
132
```bash
133
#!/bin/bash
134
# Convert all DM files in directory
135
136
for file in *.dm4; do
137
echo "Converting $file..."
138
ncem2png "$file" -o ./converted/ --scale linear --colormap gray
139
done
140
141
echo "Batch conversion complete"
142
```
143
144
### Python Integration
145
146
You can also use the command-line functionality from within Python scripts:
147
148
```python
149
import ncempy.command_line.ncem2png as ncem2png
150
import subprocess
151
import os
152
153
# Method 1: Use the module functions directly
154
success = ncem2png.dm_to_png('image.dm4', 'output.png',
155
scale='linear', colormap='gray', dpi=150)
156
157
if success:
158
print("Conversion successful")
159
160
# Method 2: Call command-line tool from Python
161
def batch_convert_directory(input_dir, output_dir):
162
"""Convert all microscopy files in directory"""
163
os.makedirs(output_dir, exist_ok=True)
164
165
for filename in os.listdir(input_dir):
166
if filename.endswith(('.dm3', '.dm4', '.ser')):
167
input_path = os.path.join(input_dir, filename)
168
169
# Call ncem2png command-line tool
170
cmd = ['ncem2png', input_path, '-o', output_dir,
171
'--scale', 'linear', '--colormap', 'gray']
172
173
result = subprocess.run(cmd, capture_output=True, text=True)
174
175
if result.returncode == 0:
176
print(f"✓ Converted {filename}")
177
else:
178
print(f"✗ Failed to convert {filename}: {result.stderr}")
179
180
# Convert entire directory
181
batch_convert_directory('./microscopy_data/', './png_output/')
182
```
183
184
### Advanced Workflows
185
186
```python
187
import ncempy.command_line.ncem2png as ncem2png
188
import ncempy.io as io
189
import numpy as np
190
191
def convert_with_metadata_overlay(input_file, output_file):
192
"""Convert file and overlay metadata as text"""
193
194
# First convert to PNG
195
success = ncem2png.dm_to_png(input_file, output_file,
196
scale='linear', colormap='gray')
197
198
if success:
199
# Load original data to get metadata
200
data = io.read(input_file)
201
202
# Add metadata text overlay using PIL
203
from PIL import Image, ImageDraw, ImageFont
204
205
img = Image.open(output_file)
206
draw = ImageDraw.Draw(img)
207
208
# Create metadata text
209
metadata_text = f"Pixel Size: {data['pixelSize']} {data['pixelUnit']}\n"
210
metadata_text += f"Dimensions: {data['data'].shape}"
211
212
# Draw text on image
213
draw.text((10, 10), metadata_text, fill='white')
214
img.save(output_file)
215
216
print(f"Conversion with metadata overlay complete: {output_file}")
217
218
# Convert with metadata overlay
219
convert_with_metadata_overlay('sample.dm4', 'sample_with_metadata.png')
220
```
221
222
### Command-Line Options Reference
223
224
```bash
225
ncem2png --help
226
```
227
228
**Usage:** `ncem2png input_file [OPTIONS]`
229
230
**Options:**
231
- `-o, --output DIR`: Output directory (default: current directory)
232
- `--scale {linear,log,sqrt}`: Intensity scaling method (default: linear)
233
- `--colormap NAME`: Matplotlib colormap name (default: gray)
234
- `--dpi INTEGER`: Output resolution in DPI (default: 150)
235
- `--format {png,jpg,tiff}`: Output image format (default: png)
236
- `--frame INTEGER`: For series files, convert specific frame only
237
- `--help`: Show help message and exit
238
239
**Supported Input Formats:**
240
- Digital Micrograph files (`.dm3`, `.dm4`)
241
- SER files (`.ser`) - converts all frames or specific frame
242
- EMD files (`.emd`)
243
- MRC files (`.mrc`)
244
245
**Examples:**
246
```bash
247
# Basic conversion
248
ncem2png image.dm4
249
250
# Custom output and scaling
251
ncem2png data.ser -o ./output --scale log --colormap hot
252
253
# High-resolution conversion
254
ncem2png sample.dm3 --dpi 300 --format png
255
256
# Convert specific frame from series
257
ncem2png series.ser --frame 10 -o frame_10.png
258
```
259
260
### Integration with Other Tools
261
262
```bash
263
# Use with ImageMagick for further processing
264
ncem2png image.dm4 -o temp.png && convert temp.png -resize 50% small.png
265
266
# Use with GNU parallel for high-performance batch processing
267
ls *.dm4 | parallel ncem2png {} -o ./converted/
268
269
# Integration with find for recursive processing
270
find ./data -name "*.dm4" -exec ncem2png {} -o ./png_output/ \;
271
```
272
273
This command-line interface provides efficient access to ncempy's file conversion capabilities for automated workflows and batch processing of electron microscopy data.