Metadata-Version: 2.5
Name: pieusb
Version: 0.4.0
Summary: Interface and acquire images from the Reflecta (a.k.a PacificImage) line of film scanners.
Project-URL: Homepage, https://github.com/davide-b/pieusb
Project-URL: Issues, https://github.com/davide-b/pieusb/issues
License-Expression: GPL-3.0-or-later
License-File: LICENSE
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.11
Requires-Dist: libusb-package>=1.0.30.0
Requires-Dist: numpy>=1.23.2
Requires-Dist: pyusb>=1.3.1
Description-Content-Type: text/markdown

# pieusb

Python package to enable interfacing with USB-connected Reflecta (a.k.a. PacificImage) film and dia scanners.

# Testers wanted!

![Discord Banner 2](https://discord.com/api/guilds/1545399511654998109/widget.png?style=banner2)

## Prerequisites

### Windows

You need to swap whatever driver Windows auto-assigned to your scanner to WinUSB. It is easiest done with [Zadig](https://zadig.akeo.ie/).

### Linux

You need to add a udev rule. `pip install pieusb` installs a command that does it:

```shell
sudo pieusb-udev install
```

If sudo answers `command not found` (it searches its own PATH, without a
virtualenv's or pipx's `bin`), run `pieusb-udev install` without sudo: it prints
the full command to use. `pieusb-udev print` shows the rules, `--group NAME`
grants a group instead of the logged-in user (for headless machines), and
`pieusb-udev uninstall` removes them. To add the rule by hand instead:

```shell
sudo tee /etc/udev/rules.d/60-pieusb.rules >/dev/null <<'EOF'
SUBSYSTEM=="usb", ATTR{idVendor}=="05e3", ATTR{idProduct}=="0142", TAG+="uaccess"
SUBSYSTEM=="usb", ATTR{idVendor}=="05e3", ATTR{idProduct}=="0143", TAG+="uaccess"
SUBSYSTEM=="usb", ATTR{idVendor}=="05e3", ATTR{idProduct}=="0144", TAG+="uaccess"
SUBSYSTEM=="usb", ATTR{idVendor}=="05e3", ATTR{idProduct}=="0145", TAG+="uaccess"
EOF
sudo udevadm control --reload-rules && sudo udevadm trigger
```
If you only care about operating one scanner, you can skip the lines with irrelevant `ATTR{idProduct}`. Here is a summary of which scanners have which

| Model | `ATTR{idProduct}` |
|---|---|
| ProScan 4000 | 0143 |
| DigitDia 6000 Multiple Slide Scanner | 0142 |
| CrystalScan 7200 | 0145 |
| ProScan 7200 | 0145 |
| ProScan 10T | 0145 |
| CrystalScan 3600 | 0145 |
| DigitDia 4000 | 0142 |
| RPS 10M (aka Pacific Image PrimeFilm XAs) | 0144 |

### macOS

It *should* just work™

## Install

```shell
pip install pieusb
```

## Usage example

```python
import numpy
import pieusb
from pieusb.scanner import Scanner

for info in pieusb.get_devices():
    print(info.vendor, info.model)

def on_update(data):
    # progress runs 0.0 -> 1.0 within each phase, not across the scan
    print(f"{data.phase}: {data.progress * 100:.1f}%")

def on_complete(result):
    if result.error:
        raise result.error
    numpy.save("scan.npy", result.rgb)

with Scanner(pieusb.get_devices()[0]) as scanner:
    scanner.mode = "rgbi"
    scanner.resolution = 5000
    scanner.color_depth = 16
    scanner.tl_x, scanner.tl_y = 0, 0
    scanner.br_x, scanner.br_y = 14200, 9600

    scanner.scan(on_update, on_complete)   # returns immediately
    scanner.wait()                         # optional
```

### Scanning more than one frame

Keep one `Scanner` open for the whole batch rather than opening one per frame.
It is faster, and the reason is `reuse_calibration`:

```python
with Scanner(pieusb.get_devices()[0]) as scanner:
    scanner.resolution = 5000
    scanner.reuse_calibration = True

    for _ in range(50):
        scanner.scan(on_update, on_complete)
        scanner.wait()
```

**What calibration means here.** At the start of a pass the scanner can run a
*shading analysis*: it scans its bare light source and returns a *shading
reference*, one white level per sensor column, from which the library evens out
the columns of every image (flat-field correction). In the same step the
scanner chooses its own exposure, gain and offset per channel -- *the scanner's
own settings*. A pass that runs the shading analysis is said to calibrate; a
*calibration pass* is a short one run only for that. Auto-exposure (`auto_exp`)
is unrelated: a pass that meters the film.

The reference has to be read at least once before it can be reused, so the first
scan above runs the shading analysis whatever the option says; the rest skip it
and correct from the cached reference, which is what saves the time. The scanner
keeps the last word: when it decides its reference has gone stale -- after a
power cycle, or on its own drift checks -- it refuses the skip and that scan
runs the analysis again.

Every scan is shading-corrected either way. `reuse_calibration` only ever
determines whether a pass pays for its own shading analysis, never whether the
image gets corrected. A pass that skips it is sent the scanner's own settings
from the analysis that took the reference, so it matches that pass in level and
colour. Since the cache lives on the `Scanner`, a fresh one starts cold: a loop
that opens a `Scanner` per frame is correct but runs the analysis every time.

### Exposure

```python
scanner.exposure = 1.5        # 1.0 is the scanner's own exposure, from its shading analysis
scanner.exposure_b = 2.0      # per channel, on top of `exposure`
scanner.auto_exp = True       # or meter it; `exposure` then acts as compensation
```

The same options on every scanner, taking effect in the scan that asks for
them. `result.exposure_factor` reports what reached the sensor, per channel.
The scanner can only lengthen its exposure, so values below 1.0 are clamped to
1.0 with a warning, and the longest it reaches depends on the exposure it chose
for itself.

The device settings behind it (`exp_rel_*`, `exp_time_*`, `gain_*`, `offset_*`,
`light`) are marked `advanced` in the option table. They can be set for
debugging, and a value set there overrides what `exposure` would derive.

### Slide transport

The DigitDia 4000 and DigitDia 6000 feed slides from a magazine, the
ProScan 4000 feeds a filmstrip or slide carrier, and the RPS 10M feeds a
filmstrip. Moving the
transport is a call of its own rather than something `scan()` does for you, so
the loop above becomes:

```python
from pieusb.exceptions import EndOfStrip

with Scanner(pieusb.get_devices()[0]) as scanner:
    scanner.resolution = 5000
    scanner.reuse_calibration = True

    while True:
        scanner.scan(on_update, on_complete)
        scanner.wait()
        try:
            scanner.advance()
        except EndOfStrip:
            break
```

`advance()` blocks until the transport is idle again, and refuses to run while a
scan is in progress -- the scan worker owns the device -- so call it once
`wait()` has returned. It raises on a scanner that has no transport rather than
silently doing nothing, so `inquiry.slide_transport` is what to branch on if the
same code drives both kinds of scanner.

Keeping the frame in the gate is a matter of not calling `advance()`:
scan it twice at different exposures, or discard a pass and repeat it, then move
on when you are done with it.

`advance()` returns how many frames the medium moved, read off the scanner's
frame counter, and raises `EndOfStrip` when it moved none: the medium is at its
last frame. A ProScan 4000 or RPS 10M with a filmstrip signals its end this
way; with a slide magazine it is not yet measured.

### Centring a frame

`advance()` moves the film by a fixed distance; it does not look for the gap
between frames, so a frame can land a millimetre or so off centre. A preview
shows by how much, and `shift_image()` corrects it:

```python
from pieusb.framing import find_bands, locate_frame

scanner.resolution = 300                    # lower resolutions are no faster
scanner.scan(on_update, on_complete)        # on_complete keeps result.rgb as `preview`
scanner.wait()
px_per_mm = 300 / 25.4
frame = locate_frame(find_bands(preview, px_per_mm), preview.shape[1], px_per_mm)
if frame is not None and frame.measured and abs(frame.shift_mm) > 0.3:
    scanner.shift_image(frame.shift_mm)
```

`shift_image()` converts with the model's measured step (ProScan 4000 and
RPS 10M). The correction stays in force across `advance()`, so a roll needs
only small touch-ups after the first frame. Avoid moving back and forth: each
out-and-back move ends 0.2-0.6 mm off. `offset_frame(mm)` moves by nominal
travel instead, on any model with a transport.

`init_transport()` prepares the transport and is there for priming it before the
first scan, or for recovering after the magazine has been handled by hand. Every
scan already does this for itself.

## Status of verification

### Verified on hardware

- ProScan 10T
- RPS 10M (aka Pacific Image PrimeFilm XAs): scanning, exposure, focus and
  `autofocus()` with a filmstrip, and `advance()`, `rewind()`,
  `offset_frame()` and `shift_image()`, end of strip included
- ProScan 4000: scanning, exposure, focus and `autofocus()` with a filmstrip
  carrier, and `advance()`, `rewind()` and `offset_frame()`

### Not verified on hardware

- ProScan 4000: `eject()` and the slide carrier
- RPS 10M: `eject()`
- Slide transport on either DigitDia. The commands follow the SANE `pieusb`
  backend, but no DigitDia has been on the bench here.

# WARNING

No guarantees are made as far as hardware safety goes.

It may be possible to set certain parameters, such as scan width or height, such that the physical limits of the scanner are exceeded. This may damage your hardware.

Proceed at your own risk.
