Return ScanImage non-varying frame and ROI metadata as dict.
166823
def scanimage_metadata(self):
        """"""
        if not self.is_scanimage:
            return None
        result = {}
        try:
            framedata, roidata = read_scanimage_metadata(self._fh)
            result['FrameData'] = framedata
            result.update(roidata)
        except ValueError:
            pass
        # TODO: scanimage_artist_metadata
        try:
            result['Description'] = scanimage_description_metadata(
                self.pages[0].description)
        except Exception as exc:
            log.warning('ScanImage metadata: %s: %s',
                        exc.__class__.__name__, exc)
        return result
361362
def load_dict(self, dct):
        """"""
        for k, v in dct.items():
            setattr(self, k, v)
944888
def to_grayscale(cv2im):
    """"""
    # How strongly does each position activate the output
    grayscale_im = np.sum(np.abs(cv2im), axis=0)

    # Normalize between min and 99th percentile
    im_max = np.percentile(grayscale_im, 99)
    im_min = np.min(grayscale_im)
    grayscale_im = np.clip((grayscale_im - im_min) / (im_max - im_min), 0, 1)

    grayscale_im = np.expand_dims(grayscale_im, axis=0)
    return grayscale_im
1328435
def info(self):
        """"""
        return {'coordinates': self._coordinates(),
                'imageinfo': self._imageinfo(),
                'miscinfo': self._miscinfo(),
                'unit': self._unit()
                }
284085
def quantize_without_scipy(self, image):
        "
        w, h = image.size
        px = np.asarray(image).copy()
        memo = {}
        for j in range(w):
            for i in range(h):
                key = (px[i, j, 0], px[i, j, 1], px[i, j, 2])
                try:
                    val = memo[key]
                except KeyError:
                    val = self.convert(*key)
                    memo[key] = val
                px[i, j, 0], px[i, j, 1], px[i, j, 2] = val
        return Image.fromarray(px).convert("RGB").quantize(palette=self.palette_image())
1183063
def _getProcessedImage(self):
        """"""
        if self.imageDisp is None:
            self.imageDisp = self.image
            self.levelMin, self.levelMax = self._quickLevels(
                self.imageDisp)
            #list( map(float, self._quickLevels(self.imageDisp)))
        return self.imageDisp
172064
def imagej_metadata(data, bytecounts, byteorder):
    
    def _string(data, byteorder):
        return data.decode('utf-16' + {'>': 'be', '<': 'le'}[byteorder])

    def _doubles(data, byteorder):
        return struct.unpack(byteorder+('d' * (len(data) // 8)), data)

    def _lut(data, byteorder):
        return numpy.frombuffer(data, 'uint8').reshape(-1, 256)

    def _bytes(data, byteorder):
        return data

    metadata_types = {  # big-endian
        b'info': ('Info', _string),
        b'labl': ('Labels', _string),
        b'rang': ('Ranges', _doubles),
        b'luts': ('LUTs', _lut),
        b'plot': ('Plots', _bytes),
        b'roi ': ('ROI', _bytes),
        b'over': ('Overlays', _bytes)}
    metadata_types.update(  # little-endian
        dict((k[::-1], v) for k, v in metadata_types.items()))

    if not bytecounts:
        raise ValueError('no ImageJ metadata')

    if not data[:4] in (b'IJIJ', b'JIJI'):
        raise ValueError('invalid ImageJ metadata')

    header_size = bytecounts[0]
    if header_size < 12 or header_size > 804:
        raise ValueError('invalid ImageJ metadata header size')

    ntypes = (header_size - 4) // 8
    header = struct.unpack(byteorder+'4sI'*ntypes, data[4:4+ntypes*8])
    pos = 4 + ntypes * 8
    counter = 0
    result = {}
    for mtype, count in zip(header[::2], header[1::2]):
        values = []
        name, func = metadata_types.get(mtype, (bytes2str(mtype), read_bytes))
        for _ in range(count):
            counter += 1
            pos1 = pos + bytecounts[counter]
            values.append(func(data[pos:pos1], byteorder))
            pos = pos1
        result[name.strip()] = values[0] if count == 1 else values
    return result
897241
def mdgel_metadata(self):
        """"""
        for page in self.pages[:2]:
            if 'MDFileTag' in page.tags:
                tags = page.tags
                break
        else:
            return None
        result = {}
        for code in range(33445, 33453):
            name = TIFF.TAGS[code]
            if name not in tags:
                continue
            result[name[2:]] = tags[name].value
        return result
69003
def _normalize(image):
  """"""
  offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])
  image -= offset

  scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])
  image /= scale
  return image
807322
def _metadata(image, datapath):
    
    metadata = {'series_number': 0, 'datadir': datapath}
    spacing = image.GetSpacing()
    metadata['voxelsize_mm'] = [
        spacing[2],
        spacing[0],
        spacing[1],
    ]
    return metadata
165763
def _coarsenImage(image, f):
    '''
    
    '''
    from skimage.morphology import square
    from skimage.filters import rank
    from skimage.transform._warps import rescale
    selem = square(f)
    arri = rank.mean(image, selem=selem)
    return rescale(arri, 1 / f, order=0)
1039390
def getProfileImage(self, name):
        
        for p in self.persons:
            if 'pseudo' in self.persons[p]:
                if name == self.persons[p]['pseudo']:
                    image_id = self.persons[p]['face']['id']
                    key = self.persons[p]['face']['key']
                    return self.getCameraPicture(image_id, key)
        return None, None
305879
def posterior_to_xarray(self):
        """"""
        data = {}
        for i, var_name in enumerate(self.var_names):
            data[var_name] = np.expand_dims(self.posterior[i], axis=0)
        return dict_to_dataset(data, library=self.tfp, coords=self.coords, dims=self.dims)
493882
def get_qpimage(self, idx):
        """"""
        if self._bgdata:
            # The user has explicitly chosen different background data
            # using `get_qpimage_raw`.
            qpi = super(SeriesHdf5Qpimage, self).get_qpimage(idx)
        else:
            # We can use the background data stored in the qpimage hdf5 file
            with self._qpseries() as qps:
                qpi = qps.get_qpimage(index=idx).copy()
            # Force meta data
            for key in self.meta_data:
                qpi[key] = self.meta_data[key]
            # set identifier
            qpi["identifier"] = self.get_identifier(idx)
        return qpi
726826
def ReadTif(tifFile):
        """"""
        img = Image.open(tifFile)
        img = np.array(img)
        return img
1183319
def imread(img, color=None, dtype=None):
    '''
    
    '''
    COLOR2CV = {'gray': cv2.IMREAD_GRAYSCALE,
                'all': cv2.IMREAD_COLOR,
                None: cv2.IMREAD_ANYCOLOR
                }
    c = COLOR2CV[color]
    if callable(img):
        img = img()
    elif isinstance(img, string_types):
        #         from_file = True
        #         try:
        #             ftype = img[img.find('.'):]
        #             img = READERS[ftype](img)[0]
        #         except KeyError:
        # open with openCV
        # grey - 8 bit
        if dtype in (None, "noUint") or np.dtype(dtype) != np.uint8:
            c |= cv2.IMREAD_ANYDEPTH
        img2 = cv2.imread(img, c)
        if img2 is None:
            raise IOError("image '%s' is not existing" % img)
        img = img2

    elif color == 'gray' and img.ndim == 3:  # multi channel img like rgb
        # cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #cannot handle float64
        img = toGray(img)
    # transform array to uint8 array due to openCV restriction
    if dtype is not None:
        if isinstance(img, np.ndarray):
            img = _changeArrayDType(img, dtype, cutHigh=False)

    return img
442051
def to_dict(self):
        """"""
        result = {}
        for meta in self.intervals.values():
            result[meta.display] = meta.value
        return result