def array2pil(a): if a.dtype==dtype("B"): if a.ndim==2: return PIL.Image.frombytes("L",(a.shape[1],a.shape[0]),a.tostring()) elif a.ndim==3: return PIL.Image.frombytes("RGB",(a.shape[1],a.shape[0]),a.tostring()) else: raise OcropusException("bad image rank") elif a.dtype==dtype('float32'): return PIL.Image.fromstring("F",(a.shape[1],a.shape[0]),a.tostring()) else: raise OcropusException("unknown image type")
def read_image_gray(fname, pageno=0): """Read an image and returns it as a floating point array. The optional page number allows images from files containing multiple images to be addressed. Byte and short arrays are rescaled to the range 0...1 (unsigned) or -1...1 (signed).""" if type(fname) == tuple: fname, pageno = fname assert pageno == 0 if issubclass(type(fname), PIL.Image.Image): pil = fname else: pil = PIL.Image.open(fname) a = pil2array(pil) if a.dtype == dtype('uint8'): a = a / 255.0 if a.dtype == dtype('int8'): a = a / 127.0 elif a.dtype == dtype('uint16'): a = a / 65536.0 elif a.dtype == dtype('int16'): a = a / 32767.0 elif isfloatarray(a): pass else: raise OcropusException("unknown image type: " + a.dtype) if a.ndim == 3: a = mean(a, 2) return a