python-sane documentation

The sane module is a Python interface to the SANE (Scanner Access Now Easy) library, which provides access to various raster scanning devices such as flatbed scanners and digital cameras. For more information about SANE, consult the SANE website at www.sane-project.org. Note that this documentation doesn’t duplicate all the information in the SANE documentation, which you must also consult to get a complete understanding.

This module has been originally developed by A.M. Kuchling, it is currently maintained by Sandro Mani.

Installation

Basic Installation using pip

Before you begin, ensure that the libsane-dev package is installed on your system. This is a required dependency.

On Debian-based system (like Ubuntu), you can install libsane-dev using the apt package manager.

apt install libsane-dev

Then install the packages via pip

pip install python-sane

Building from sources

You can find the instructions on how to build and install from sources in the main README.rst

Indices

Reference

sane.exit()

Exit sane.

sane.get_devices(localOnly=False)

Return a list of 4-tuples containing the available scanning devices. If localOnly is True, only local devices will be returned. Each tuple is of the format (device_name, vendor, model, type), with:

  • device_name – The device name, suitable for passing to sane.open().

  • vendor – The device vendor.

  • model – The device model vendor.

  • type – the device type, such as "virtual device" or "video camera".

Returns:

A list of scanning devices.

Raises:

_sane.error – If an error occurs.

sane.init()

Initialize sane.

Returns:

A tuple (sane_ver, ver_maj, ver_min, ver_patch).

Raises:

_sane.error – If an error occurs.

sane.open(devname)

Open a device for scanning. Suitable values for devname are returned in the first item of the tuples returned by sane.get_devices().

Returns:

A SaneDev object on success.

Raises:

_sane.error – If an error occurs.

class sane.SaneDev(devname)

Class representing a SANE device. Besides the functions documented below, the class has some special attributes which can be read:

  • devname – The scanner device name (as passed to

    sane.open()).

  • sane_signature – The tuple (devname, brand, name, type).

  • scanner_model – The tuple (brand, name).

  • opt – Dictionary of options.

  • optlist – List of option names.

  • area – Scan area.

Furthermore, the scanner options are also exposed as attributes, which can be read and set:

print(scanner.mode)
scanner.mode = 'Color'

An Option object for a scanner option can be retrieved via __getitem__(), i.e.:

option = scanner['mode']
arr_scan(progress=None)

Convenience method which calls SaneDev.start() followed by SaneDev.arr_snap().

arr_snap(progress=None)

Read image data and return a 3d numpy array of the shape (width, height, nbands).

Returns:

A numpy.array object.

Raises:
  • _sane.error – If an error occurs.

  • RuntimeError – If numpy cannot be imported.

cancel()

Cancel an in-progress scanning operation.

close()

Close the scanning device.

fileno()
Returns:

The file descriptor for the scanning device, if any.

Raises:

_sane.error – If an error occurs.

get_options()
Returns:

A list of tuples describing all the available options.

get_parameters()

Returns a 5-tuple holding all the current device settings: (format, last_frame, (pixels_per_line, lines), depth, bytes_per_line)

  • format – One of "grey", "color", "red",

    "green", "blue" or "unknown format".

  • last_frame – Whether this is the last frame of a multi frame

    image.

  • pixels_per_line – Width of the scanned image.

  • lines – Height of the scanned image.

  • depth – The number of bits per sample.

  • bytes_per_line – The number of bytes per line.

Returns:

A tuple containing the device settings.

Raises:

_sane.error – If an error occurs.

Note: Some backends may return different parameters depending on whether SaneDev.start() was called or not.

multi_scan()
Returns:

A _SaneIterator for ADF scans.

scan(progress=None)

Convenience method which calls SaneDev.start() followed by SaneDev.snap().

snap(no_cancel=False, progress=None)

Read image data and return a PIL.Image object. An RGB image is returned for multi-band images, an L image for single-band images. no_cancel is used for ADF scans by _SaneIterator.

Returns:

A PIL.Image object.

Raises:
  • _sane.error – If an error occurs.

  • RuntimeError – If PIL.Image cannot be imported.

start()

Initiate a scanning operation.

Throws _sane.error:

If an error occurs, for instance if an option is set to an invalid value.

class sane.Option(args, scanDev)

Class representing a SANE option. These are returned by a SaneDev.__getitem__() lookup of an option on the device, i.e.:

option = scanner["mode"]

The Option class has the following attributes:

  • index – Number from 0 to n, giving the option number.

  • name – A string uniquely identifying the option.

  • title – Single-line string containing a title for the option.

  • desc – A long string describing the option, useful as a help

    message.

  • type – Type of this option: TYPE_BOOL, TYPE_INT,

    TYPE_STRING, etc.

  • unit – Units of this option. UNIT_NONE, UNIT_PIXEL, etc.

  • size – Size of the value in bytes.

  • cap – Capabilities available: CAP_EMULATED, CAP_SOFT_SELECT,

    etc.

  • constraint – Constraint on values. Possible values:

    • None : No constraint

    • (min,max,step) : Range

    • list of integers or strings: listed of permitted values

is_active()
Returns:

Whether the option is active.

is_settable()
Returns:

Whether the option is settable.

class sane._SaneIterator(device)

Iterator for ADF scans.

Example

 1#!/usr/bin/env python
 2
 3import sane
 4import numpy
 5from PIL import Image
 6
 7#
 8# Change these for 16bit / grayscale scans
 9#
10depth = 8
11mode = 'color'
12
13#
14# Initialize sane
15#
16ver = sane.init()
17print('SANE version:', ver)
18
19#
20# Get devices
21#
22devices = sane.get_devices()
23print('Available devices:', devices)
24
25#
26# Open first device
27#
28dev = sane.open(devices[0][0])
29
30#
31# Set some options
32#
33params = dev.get_parameters()
34try:
35    dev.depth = depth
36except Exception:
37    print('Cannot set depth, defaulting to %d' % params[3])
38
39try:
40    dev.mode = mode
41except Exception:
42    print('Cannot set mode, defaulting to %s' % params[0])
43
44try:
45    dev.br_x = 320.
46    dev.br_y = 240.
47except Exception:
48    print('Cannot set scan area, using default')
49
50params = dev.get_parameters()
51print(
52    'Device parameters:', params,
53    '\n Resolutions %d, x %d, y %d '
54    % (dev.resolution, dev.x_resolution, dev.y_resolution)
55)
56
57#
58# Start a scan and get a PIL.Image object
59#
60dev.start()
61im = dev.snap()
62im.save('test_pil.png')
63
64
65#
66# Start another scan and get a numpy array object
67#
68# Initiate the scan and get a numpy array
69dev.start()
70arr = dev.arr_snap()
71print("Array shape: %s, size: %d, type: %s, range: %d-%d, mean: %.1f, stddev: "
72      "%.1f" % (repr(arr.shape), arr.size, arr.dtype, arr.min(), arr.max(),
73                arr.mean(), arr.std()))
74
75if arr.dtype == numpy.uint16:
76    arr = (arr / 255).astype(numpy.uint8)
77
78# reshape needed by PIL library
79arr = arr.reshape(arr.shape[2], arr.shape[1], arr.shape[0])
80if params[0] == 'color':
81    im = Image.frombytes('RGB', arr.shape[1:], arr.tostring(), 'raw', 'RGB', 0,
82                         1)
83else:
84    im = Image.frombytes('L', arr.shape[1:], arr.tostring(), 'raw', 'L', 0, 1)
85
86im.save('test_numpy.png')
87
88#
89# Close the device
90#
91dev.close()