Automating OM-1 macro focus stacking: from SD card to finished image


How I automated my OM-1 macro photography workflow with Python, LibRaw and focus-stack

TL;DR

Insert SD card, run the script, and let the Mac do the dull bits. My OM-1 macro workflow groups frames into focus stacks, converts ORF RAW files to 16-bit TIFF, runs focus-stack, and puts the finished images in an output folder. The tools are open source: Python, LibRaw, focus-stack, exiftool and YAML.

The problem: macro stacking takes too many clicks

At macro distances, the depth of field becomes paper-thin. To get a whole subject sharp, I shoot multiple frames with different focus positions and combine them. The stacking itself is manageable; repeatedly preparing the files is the exhausting part.

My old manual routine

  1. Shoot roughly 10–50 frames of a subject.
  2. Put the SD card in the Mac.
  3. Work out which images belong together.
  4. Convert ORF files to TIFF.
  5. Load each set into a stacking application.
  6. Wait, export, and do it again for the next set.

Five to ten stacks in one session? No thanks.

The idea: automate the whole thing

The ideal workflow is: insert card, run one command, make coffee, find finished images in the output directory. That is what I wanted to build.

SD-Karte einstecken
    ↓
Script starten
    ↓
☕ Kaffee trinken
    ↓
Fertige Bilder im Output-Ordner

What I'm using

Hardware

  • Camera: OM System OM-1 (the workflow is based on ORF files; other models may need adjustments)
  • Computer: Intel or Apple Silicon Mac
  • Card reader: Whatever reliably mounts the SD card

Software

Tool Job Why I picked it
Python 3 Orchestration Flexible and easy to extend
LibRaw / dcraw_emu RAW conversion Handles newer camera RAW formats
focus-stack Stacking An open-source command-line tool
exiftool Metadata Lets me group frames by capture time
PyYAML Settings Comments and readable configuration

A GPS logger is optional if you want locations attached to the images.

Under the hood

The steps are deliberately separated so I can debug one stage without rebuilding the entire workflow.

1. Find the SD card

The Mac mounts external media under /Volumes/. I look for mounted volumes containing a DCIM folder, then count ORF files. The configuration supports ask (choose interactively), first (use the first detected card), and manual (a fixed folder).

def find_sd_cards(self):
    volumes_path = Path("/Volumes")
    sd_cards = []

    for volume in volumes_path.iterdir():
        dcim_path = volume / "DCIM"
        if dcim_path.exists() and dcim_path.is_dir():
            orf_count = len(list(dcim_path.rglob("*.ORF")))
            sd_cards.append({
                'name': volume.name,
                'dcim': dcim_path,
                'orf_count': orf_count
            })

    return sd_cards

2. Group images using EXIF capture times

Focus-bracketed images are usually taken seconds apart. I sort by capture time and start a new series when the time gap exceeds a configurable threshold — 30 seconds in my example. That is less brittle than trusting filename sequences, although camera clocks and malformed metadata still need checking.

For instance, frames at 10:15:00, 10:15:02 and 10:15:04 form one set; frames at 10:20 form another.

def find_series(self, images):
    threshold = timedelta(seconds=self.config['time_threshold'])

    for img, timestamp in sorted_images:
        if last_time and (timestamp - last_time) > threshold:
            # Neue Serie!
            series.append(current_series)
            current_series = [img]
        else:
            current_series.append(img)

3. Convert RAW files: why I moved beyond dcraw

The traditional dcraw utility predates the OM-1 and can fail on its ORF files. LibRaw's dcraw_emu is the practical replacement here. I use -6 for 16-bit output, because gradients and shadow detail matter when multiple images get combined.

One quirk: it may output image.ORF.tiff rather than image.tiff, so my script handles the filename.

# OM-1 ORF zu 16-bit TIFF
dcraw_emu -6 -T -w -o 1 -q 3 image.ORF

4. Stack with focus-stack

I wanted a tool that I could call without opening a GUI. That makes focus-stack a natural fit. Commercial tools such as Helicon Focus or Zerene Stacker are alternatives when their output or features justify the price.

The example sets consistency=3 and denoise=0.5. Raise consistency for strict alignment; lower it for more tolerance. Denoising is a trade-off between smooth results and detail. Check the command syntax against your installed focus-stack release before copying examples with inline comments.

focus-stack \
  --output=result.jpg \
  --consistency=3 \      # Alignment-Strenge (2-5)
  --denoise=0.5 \        # Leichte Rauschunterdrückung
  *.tiff

5. Orchestrate the work

The Python controller copies input files to local temporary storage, converts ORF images to TIFF, stacks each series, and removes temporary work files. Copying first also avoids intermittent issues I have seen when working directly from SD cards.

def stack_series(self, images, output_name):
    # 1. Bilder kopieren (SD-Karte → /tmp)
    copied_images = self.copy_images(images)

    # 2. RAW konvertieren (ORF → 16-bit TIFF)
    tiff_files = self.convert_raw(copied_images)

    # 3. Stacking
    self.focus_stack(tiff_files, output_name)

    # 4. Cleanup
    self.cleanup_temp()

Configuration: YAML wins over JSON

I initially used JSON keys with names like _comment_*. They were a clumsy substitute for real comments. YAML gives me a readable configuration where I can document thresholds, paths and processing settings right beside their values.

# ═══════════════════════════════════════════
# OM-1 Makro-Stacking Pipeline
# ═══════════════════════════════════════════

# SD-Karten-Modus
# 'ask' = immer fragen
# 'first' = erste nehmen
# 'manual' = fester Pfad
sd_card_mode: ask

# Serien-Erkennung
# Max. Sekunden zwischen Bildern einer Serie
time_threshold: 30

# Mindestanzahl Bilder pro Serie
min_images: 3

# Stacking-Software
stacker: focus-stack
stacker_binary: ~/bin/focus-stack/focus-stack.app/Contents/MacOS/focus-stack

# focus-stack Parameter
consistency: 3      # 2-5, höher = strenger
denoise: 0.5        # 0-2, Rauschunterdrückung

# RAW-Konvertierung
convert_raw: true
raw_converter: libraw

# Output
output_dir: ~/Pictures/Stacked
output_format: jpg
output_quality: 95

Installation

The commands below reflect the macOS setup I used. Install dependencies appropriate to your machine, verify downloaded software, and check binary paths before running the workflow.

Step 1: dependencies

Install Homebrew if required, then Python, exiftool and LibRaw. Install PyYAML for the configuration file. For modern Python setups, a virtual environment is usually preferable to a system-wide pip3 install.

# Homebrew (falls noch nicht installiert)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Tools installieren
brew install python3 exiftool libraw

# Python-Dependencies
pip3 install pyyaml

Step 2: focus-stack

Download the macOS release from the upstream project, unpack it, put it in a directory on your path and run its help command. The exact bundle layout differs by release, so don't blindly assume every archive unpacks to the same executable path.

# Download von GitHub Releases
cd ~/Downloads
# https://github.com/PetteriAimonen/focus-stack/releases
# → focus-stack-macos.zip herunterladen

# Entpacken und installieren
unzip focus-stack-*.zip
mkdir -p ~/bin
mv focus-stack ~/bin/
chmod +x ~/bin/focus-stack

# Testen
~/bin/focus-stack --help

Step 3: create the script

Create a scripts folder, paste the full Python program from the next section into macro_stacking.py and make it executable.

# Ordner erstellen
mkdir -p ~/scripts

# Script erstellen
nano ~/scripts/macro_stacking.py
# (Code einfügen – siehe unten)

# Ausführbar machen
chmod +x ~/scripts/macro_stacking.py

Step 4: first run

The first run creates a config file. Open ~/.stacking_config.yaml and adjust the SD-card mode, paths and stacking parameters.

# Erstellt Config-Datei
python3 ~/scripts/macro_stacking.py

# Config anpassen
nano ~/.stacking_config.yaml

The full Python script

Here is the complete script from my setup. I have kept the source code exactly as it appears in the German original, including comments and strings, so its behavior is not silently changed by translation. Review its assumptions and test it on copies of photos before trusting it with your only originals.

#!/usr/bin/env python3
"""
Automatischer Makro-Stacking-Workflow für OM-1 auf macOS
"""

import os
import subprocess
import shutil
from pathlib import Path
from datetime import datetime, timedelta

class OM1StackingPipeline:

    def __init__(self, config_path="~/.stacking_config.yaml"):
        self.config = self.load_config(config_path)
        self.output_dir = Path(self.config['output_dir']).expanduser()
        self.temp_dir = Path(self.config['temp_dir']).expanduser()
        self.stacker_bin = Path(self.config['stacker_binary']).expanduser()

        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.temp_dir.mkdir(parents=True, exist_ok=True)

    def load_config(self, path):
        """Config laden oder Default erstellen"""
        config_path = Path(path).expanduser()

        if not config_path.exists():
            # Default-Config mit Kommentaren erstellen
            default_config = """# OM-1 Makro-Stacking Pipeline

sd_card_mode: ask
time_threshold: 30
min_images: 3

stacker: focus-stack
stacker_binary: ~/bin/focus-stack

consistency: 3
denoise: 0.5

convert_raw: true
raw_converter: libraw

output_dir: ~/Pictures/Stacked
output_format: jpg
output_quality: 95
"""
            config_path.parent.mkdir(parents=True, exist_ok=True)
            with open(config_path, 'w') as f:
                f.write(default_config)

            import yaml
            return yaml.safe_load(default_config)

        import yaml
        with open(config_path) as f:
            return yaml.safe_load(f)

    def find_sd_cards(self):
        """SD-Karten mit DCIM-Ordner finden"""
        volumes_path = Path("/Volumes")
        sd_cards = []

        for volume in volumes_path.iterdir():
            if not volume.is_dir():
                continue

            # System-Volumes überspringen
            if volume.name in ['Macintosh HD', 'Preboot', 'Recovery', 'VM', 'Data']:
                continue

            dcim_path = volume / "DCIM"
            if dcim_path.exists():
                orf_count = len(list(dcim_path.rglob("*.ORF")))
                sd_cards.append({
                    'name': volume.name,
                    'dcim': dcim_path,
                    'orf_count': orf_count
                })

        return sd_cards

    def select_sd_card(self, sd_cards):
        """SD-Karte auswählen"""
        mode = self.config.get('sd_card_mode', 'ask')

        if mode == 'first':
            return sd_cards[0]
        elif mode == 'ask':
            print("\n📸 SD-Karten gefunden:\n")
            for i, card in enumerate(sd_cards, 1):
                print(f"  [{i}] {card['name']} ({card['orf_count']} ORF-Files)")

            choice = input("\nWelche SD-Karte? [1]: ").strip() or "1"
            return sd_cards[int(choice) - 1]

    def find_series(self, images):
        """Bilder in Serien gruppieren via EXIF-Timestamp"""
        # EXIF-Daten auslesen
        images_with_time = []
        for img in images:
            timestamp = self.get_exif_data(img)
            if timestamp:
                images_with_time.append((img, timestamp))

        # Nach Zeit sortieren
        images_with_time.sort(key=lambda x: x[1])

        # Serien erkennen
        series = []
        current_series = []
        last_time = None
        threshold = timedelta(seconds=self.config['time_threshold'])

        for img, timestamp in images_with_time:
            if last_time and (timestamp - last_time) > threshold:
                if len(current_series) >= self.config['min_images']:
                    series.append(current_series)
                current_series = [img]
            else:
                current_series.append(img)
            last_time = timestamp

        if len(current_series) >= self.config['min_images']:
            series.append(current_series)

        return series

    def convert_raw(self, orf_file, output_dir):
        """ORF zu 16-bit TIFF konvertieren"""
        subprocess.run([
            'dcraw_emu',
            '-6',  # 16-bit!
            '-T',  # TIFF
            '-w',  # Camera WB
            '-o', '1',  # sRGB
            '-q', '3',  # Best quality
            orf_file.name
        ], cwd=str(output_dir), check=True, capture_output=True)

        # Umbenennen: image.ORF.tiff → image.tiff
        output_raw = output_dir / f"{orf_file.name}.tiff"
        output = output_dir / f"{orf_file.stem}.tiff"
        output_raw.rename(output)

        return output

    def stack_series(self, images, output_name):
        """Serie stacken"""
        temp_dir = self.temp_dir / output_name
        temp_dir.mkdir(parents=True, exist_ok=True)

        print(f"  📸 Stacke {len(images)} Bilder...")

        # 1. Kopieren
        copied = [shutil.copy2(img, temp_dir / img.name) for img in images]

        # 2. Konvertieren
        print(f"  🔄 Konvertiere RAW...")
        converted = []
        for i, img in enumerate([Path(p) for p in copied], 1):
            print(f"    [{i}/{len(copied)}] {img.name}", end=" ")
            try:
                tiff = self.convert_raw(img, temp_dir)
                converted.append(tiff)
                print("✓")
            except:
                print("✗")

        # 3. Stacking
        print(f"  🔬 Stacking...")
        output_file = self.output_dir / f"{output_name}.{self.config['output_format']}"

        subprocess.run([
            str(self.stacker_bin),
            f'--output={output_file}',
            f'--consistency={self.config["consistency"]}',
            f'--denoise={self.config["denoise"]}',
            *[str(img) for img in converted]
        ], check=True, capture_output=True)

        # 4. Cleanup
        shutil.rmtree(temp_dir)

        return output_file

    def run(self):
        """Haupt-Pipeline"""
        print("╔═══════════════════════════════════════════╗")
        print("║  OM-1 Makro-Stacking Pipeline            ║")
        print("╚═══════════════════════════════════════════╝")

        # SD-Karte finden
        print("\n🔍 Suche SD-Karten...")
        sd_cards = self.find_sd_cards()

        if not sd_cards:
            print("❌ Keine SD-Karte gefunden!")
            return

        selected = self.select_sd_card(sd_cards)

        # Bilder finden
        images = list(selected['dcim'].rglob("*.ORF"))
        print(f"\n✓ Gefunden: {len(images)} Bilder")

        # Serien erkennen
        series = self.find_series(images)
        print(f"✓ Erkannt: {len(series)} Serien\n")

        # Stacking
        success = 0
        for i, imgs in enumerate(series, 1):
            timestamp = self.get_exif_data(imgs[0])
            series_name = f"series_{timestamp.strftime('%Y%m%d_%H%M%S')}"

            print(f"━━━ Serie {i}/{len(series)}: {series_name} ━━━")

            try:
                output = self.stack_series(imgs, series_name)
                print(f"  ✓ Fertig: {output.name}\n")
                success += 1
            except Exception as e:
                print(f"  ❌ Fehler: {e}\n")

        print(f"╔═══════════════════════════════════════════╗")
        print(f"║  ✓ {success}/{len(series)} Serien gestackt! ║")
        print(f"╚═══════════════════════════════════════════╝")

if __name__ == "__main__":
    try:
        pipeline = OM1StackingPipeline()
        pipeline.run()
    except KeyboardInterrupt:
        print("\n⚠️  Abgebrochen")

How to use it

The standard workflow

Insert the SD card, open Terminal, and run the Python script. The example terminal output illustrates what the workflow is meant to report as it finds, converts and stacks a series.

# 1. SD-Karte einstecken
# 2. Terminal öffnen
# 3. Script starten
python3 ~/scripts/macro_stacking.py
╔═══════════════════════════════════════════╗
║  OM-1 Makro-Stacking Pipeline            ║
╚═══════════════════════════════════════════╝

🔍 Suche SD-Karten...

📸 SD-Karten gefunden:

  [1] untitled (42 ORF-Files)

Welche SD-Karte? [1]: 

✓ Gefunden: 42 Bilder

📊 Analysiere Bilder...
✓ Erkannt: 3 Serien

━━━ Serie 1/3: series_20260314_083628 ━━━
  📸 Stacke 16 Bilder...
  🔄 Konvertiere RAW...
    [1/16] P3141806.ORF ✓
    [2/16] P3141807.ORF ✓
    ...
  🔬 Stacking...
  ✓ Fertig: series_20260314_083628.jpg

━━━ Serie 2/3: series_20260314_091522 ━━━
  ...

╔═══════════════════════════════════════════╗
║  ✓ 3/3 Serien gestackt!                   ║
╚═══════════════════════════════════════════╝

More than one SD card

With sd_card_mode: ask, the tool lists candidate volumes and asks me to pick one. Handy when an external drive also happens to contain a DCIM directory.

📸 SD-Karten gefunden:

  [1] untitled (42 ORF-Files)
  [2] EOS_DIGITAL (18 ORF-Files)

Welche SD-Karte? [1]: 2

✓ Gewählt: EOS_DIGITAL

Run without questions

For a repeatable unattended workflow, select first in the YAML configuration. Be aware that 'first detected card' is a convenience, not a guaranteed way to choose the intended card if multiple drives are attached.

# Config: ~/.stacking_config.yaml
sd_card_mode: first  # Nimmt automatisch erste Karte
python3 ~/scripts/macro_stacking.py
# Keine Interaktion nötig!

Extras

GPS tagging

When shooting outside, I can record a GPX track on my phone, export it and reference it in the settings. The sample shows the additional configuration and exiftool command. Check camera time zones and clock drift: GPS matching is only as good as the timestamps.

gpx_file: ~/Downloads/track_20260314.gpx
🌍 Füge GPS-Daten hinzu: track_20260314.gpx
  ✓ GPS-Daten hinzugefügt

Debug mode

Turn on debug and keep_temp to inspect intermediate TIFF files. If the result looks wrong, these are the files I want to see before blaming the stacking engine.

debug: true
keep_temp: true

Tuning the parameters

For difficult subjects I use more conservative alignment and minimal smoothing; for speed I relax consistency and allow a bit more denoising. I treat these as starting points, not universal settings.

consistency: 5      # Sehr streng (weniger Fehler)
denoise: 0          # Kein Denoise (maximale Schärfe)
consistency: 2      # Toleranter (schneller)
denoise: 1.5        # Mehr Glättung
consistency: 3
denoise: 0.5

Troubleshooting

The biggest gains come from checking the simple things first: whether the card is mounted, whether required executables exist, and whether the images actually form a good focus series.

The script can't find an SD card

Check /Volumes/ and whether the mounted volume contains a DCIM directory. macOS permissions, a missing mount or an unexpected directory structure can all get in the way. A manual path is a useful workaround.

ls /Volumes/
ls /Volumes/*/DCIM/
# Config: Manuellen Pfad nutzen
sd_card_mode: manual
watch_dir: /Volumes/MEINE_KARTE/DCIM

dcraw_emu: command not found

Install LibRaw and confirm that the command is reachable on your shell's PATH.

# LibRaw installieren
brew install libraw

# Checken
which dcraw_emu
dcraw_emu --version

focus-stack crashes

Possible causes include memory pressure, damaged TIFF files, and movement between frames. Keep the temporary images, inspect them, then try running the stacking command directly.

keep_temp: true

The stack doesn't look sharp

Check that conversion produced 16-bit TIFF files, that you captured enough frames with overlapping focus zones, and that the subject didn't move too much. A tripod helps, but even tiny changes in wind can ruin a macro stack.

Unexpected end of file during RAW conversion

Reading directly from a slow or unreliable SD card was a suspected cause in my workflow, so I copy files to local storage first. If it still happens, inspect the source file and try another temporary directory rather than assuming USB latency is always responsible.

# Anderes Temp-Verzeichnis
temp_dir: ~/tmp/stacking

Performance

These were my example results on an M1 MacBook Pro with 20-megapixel ORF files — not universal benchmarks:

Stack size Frames RAW to TIFF Stacking Total
Small 7 12 s 8 s 20 s
Medium 16 28 s 22 s 50 s
Large 32 58 s 65 s 2 min 3 s

Larger stacks cost more time and memory, but I get that time back by not babysitting every stage.

What I learned

1. Use a converter that knows your camera

Traditional dcraw was a poor match for my newer ORF files. LibRaw and dcraw_emu have been more useful in this setup. If you see conversion errors, test a single file before debugging the rest of the pipeline.

2. Keep the 16-bit data

Converting to eight bits too early risks posterization and lost tonal detail. With high-ISO macro photos, preserving 16-bit TIFF data through processing gives me more room to work, even though it doesn't magically restore information that was never captured.

3. EXIF grouping beats filename guessing

Camera counters wrap or reset, images from different sessions get mixed, and there may be missing numbers. Capture timestamps are a better first clue. They are not infallible, though; incorrect camera time settings can still mislead the grouping logic.

4. Comments make configuration usable

Compare the fake comment key in JSON with the straightforward YAML comment. This is why I prefer YAML for a configuration that I might need to tweak months later.

{
  "_comment_consistency": "2-5, höher = strenger",
  "consistency": 3
}
# Consistency-Level (2-5, höher = strenger)
consistency: 3

5. Copy locally before processing

Local temporary copies reduce dependence on a removable card and make conversion easier to reproduce. USB hiccups, exFAT quirks and slow readers are less likely to interfere once the images are safely copied.

Where I could take it next

My wishlist includes processing separate series in parallel, launching automatically when a card is inserted, a small progress dashboard, image-quality checks, automatic NAS or cloud backups, optional Helicon Focus support, Linux/Windows support and batch reprocessing of old sessions. None of those are prerequisites for the current workflow.

Other options

Why not another tool?

  • Lightroom/Photoshop: powerful editors, but a less direct fit for this unattended workflow and usually subscription-based.
  • Helicon Focus: polished commercial option, potentially better suited to demanding stacks, but another paid tool and different automation constraints.
  • Zerene Stacker: also capable, but not my first pick for simple shell-based automation.
  • shinestacker: interesting open-source route, with a different integration model.
  • Do it manually: works, but costs time and makes it harder for me to repeat the same processing parameters across sessions.

Conclusion

The result is a workflow that no longer needs me to sort image sequences, convert RAW frames by hand or keep opening dialogs. Once I have tuned the setup and verified the outputs, it's pleasantly boring: take photographs, start the script, and collect the stacks. That's exactly how automation should feel.

Downloads and upstream projects

The original article had placeholder links for a future public script repository and configuration download, so I won't pretend those files are published. The actual script is included above.

More posts from this series

Questions or improvements? I'm always interested in hearing what works on different cameras and Macs.

Previous Next