Search code examples
pythonimagetiffendiannesssane

Create a 16 Bit TIFF image from a Python string


I need to use scanner in 16 bit depth and color mode, so i modified python-imaging-sane (that doesn't support RGB tiff with 16 bit depth) to receive from a scanner (epson v500) an image in a Python string.

this is the modified function that i use to send data from the scanner to a python string:

#define READSIZE 32768

static PyObject *
SaneDev_read(SaneDevObject *self, PyObject *args)
{
SANE_Status st;
unsigned char c_buf[READSIZE];
SANE_Int len, maxlen;
maxlen = READSIZE;
if (!PyArg_ParseTuple(args, ""))
{
        return NULL;
}
st = (int) sane_read(self->h, (SANE_Byte *) c_buf, maxlen, &len);
return Py_BuildValue("is#", st, c_buf, len);
}

i use this python script to receive and use data:

import sane
import pgmagick
import cStringIO

sane.init()

s = sane.open(sane.get_devices()[0][0])

s.mode = 'Color'
s.source = 'Transparency Unity'

s.tl_x = 15
s.tl_y = 30
s.br_x = 52
s.br_y = 55

s.x_resolution = 1600
s.y_resolution = 1600

s.depth = 16

fbuffer = cStringIO.StringIO()

s.start()

par = s.get_parameters()
print "par = ", par

st = 0
while st is 0:
    st, buf = s.read()
    fbuffer.write(buf)

s.cancel()

data = fbuffer.getvalue()
fbuffer.close()

px = par[2][0]
py = par[2][1]
bytesperlines = par[4]
depth = par[3]

size = "%sx%s" % (px, py)
blob = pgmagick.Blob(data)
im  = pgmagick.Image()
im.density("1600x1600")
im.depth(depth)
im.size(size)
im.magick('RGB')
im.resolutionUnits(gm.ResolutionType.PixelsPerInchResolution)
im.read(blob)
im.write("img.tiff")

the script works very well with 8 bit depth, but with depth set to 16 bit i obtain an image with wrong colors;

these are two examples:

with 8 bit depth

with 16 bit depth

where is the problem?

EDIT: i use pgmagick, a python wrapper to graphicsmagick; graphicsmagick is compiled with quantum depth set to 16 bit.


Solution

  • You probably have the byte order wrong. Try swapping the two bytes that make up the sixteen bit data and see what you get.