Return image data from series of TIFF pages as numpy array.
438077
def asarray(self, out=None):
        """"""
        if self.parent:
            result = self.parent.asarray(series=self, out=out)
            if self.transform is not None:
                result = self.transform(result)
            return result
        return None
364587
def load_image_from_disk(img_spec):
    """"""

    if isinstance(img_spec, str):
        if pexists(realpath(img_spec)):
            hdr = nib.load(img_spec)
            # trying to stick to an orientation
            hdr = nib.as_closest_canonical(hdr)
            img = hdr.get_data()
        else:
            raise IOError('Given path to image does not exist!')
    elif isinstance(img_spec, np.ndarray):
        img = img_spec
    else:
        raise ValueError('Invalid input specified! '
                         'Input either a path to image data, or provide 3d Matrix directly.')

    return img
894549
def _download_images(data, img_cols):
  """"""

  images = collections.defaultdict(list)
  for d in data:
    for img_col in img_cols:
      if d.get(img_col, None):
        if isinstance(d[img_col], Image.Image):
          # If it is already an Image, just copy and continue.
          images[img_col].append(d[img_col])
        else:
          # Otherwise it is image url. Load the image.
          with file_io.FileIO(d[img_col], 'rb') as fi:
            im = Image.open(fi)
          images[img_col].append(im)
      else:
        images[img_col].append('')

  return images
474477
private void getYCCArray() {
        int values[] = new int[imageWidth * imageHeight];
        int r, g, b, y, x;
// In order to minimize the chance that grabPixels will throw an exception
// it may be necessary to grab some pixels every few scanlines and process
// those before going for more.  The time expense may be prohibitive.
// However, for a situation where memory overhead is a concern, this may be
// the only choice.
        PixelGrabber grabber = new PixelGrabber(imageobj.getSource(), 0, 0, imageWidth, imageHeight, values, 0, imageWidth);
        int maxHsampFactor = 1;
        int maxVsampFactor = 1;
        for (y = 0; y < NumberOfComponents; y++) {
            maxHsampFactor = Math.max(maxHsampFactor, HsampFactor[y]);
            maxVsampFactor = Math.max(maxVsampFactor, VsampFactor[y]);
        }
        for (y = 0; y < NumberOfComponents; y++) {
            compWidth[y] = (((imageWidth % 8 != 0) ? ((int) Math.ceil((double) imageWidth / 8.0)) * 8 : imageWidth) / maxHsampFactor) * HsampFactor[y];
            if (compWidth[y] != ((imageWidth / maxHsampFactor) * HsampFactor[y])) {
                lastColumnIsDummy[y] = true;
            }
            // results in a multiple of 8 for compWidth
            // this will make the rest of the program fail for the unlikely
            // event that someone tries to compress an 16 x 16 pixel image
            // which would of course be worse than pointless
            BlockWidth[y] = (int) Math.ceil((double) compWidth[y] / 8.0);
            compHeight[y] = (((imageHeight % 8 != 0) ? ((int) Math.ceil((double) imageHeight / 8.0)) * 8 : imageHeight) / maxVsampFactor) * VsampFactor[y];
            if (compHeight[y] != ((imageHeight / maxVsampFactor) * VsampFactor[y])) {
                lastRowIsDummy[y] = true;
            }
            BlockHeight[y] = (int) Math.ceil((double) compHeight[y] / 8.0);
        }
        try {
            grabber.grabPixels();
        } catch (InterruptedException ignored) {
        }
        float Y[][] = new float[compHeight[0]][compWidth[0]];
        float Cr1[][] = new float[compHeight[0]][compWidth[0]];
        float Cb1[][] = new float[compHeight[0]][compWidth[0]];
        int index = 0;
        for (y = 0; y < imageHeight; ++y) {
            for (x = 0; x < imageWidth; ++x) {
                r = ((values[index] >> 16) & 0xff);
                g = ((values[index] >> 8) & 0xff);
                b = (values[index] & 0xff);

// The following three lines are a more correct color conversion but
// the current conversion technique is sufficient and results in a higher
// compression rate.
//                Y[y][x] = 16 + (float)(0.8588*(0.299 * (float)r + 0.587 * (float)g + 0.114 * (float)b ));
//                Cb1[y][x] = 128 + (float)(0.8784*(-0.16874 * (float)r - 0.33126 * (float)g + 0.5 * (float)b));
//                Cr1[y][x] = 128 + (float)(0.8784*(0.5 * (float)r - 0.41869 * (float)g - 0.08131 * (float)b));
                Y[y][x] = (float) ((0.299 * (float) r + 0.587 * (float) g + 0.114 * (float) b));
                Cb1[y][x] = 128 + (float) ((-0.16874 * (float) r - 0.33126 * (float) g + 0.5 * (float) b));
                Cr1[y][x] = 128 + (float) ((0.5 * (float) r - 0.41869 * (float) g - 0.08131 * (float) b));
                index++;
            }
        }

// Need a way to set the H and V sample factors before allowing downsampling.
// For now (04/04/98) downsampling must be hard coded.
// Until a better downsampler is implemented, this will not be done.
// Downsampling is currently supported.  The downsampling method here
// is a simple box filter.

        Components[0] = Y;
//        Cb2 = DownSample(Cb1, 1);
        Components[1] = Cb1;
//        Cr2 = DownSample(Cr1, 2);
        Components[2] = Cr1;
    }
808222
def _load_data(path, labels_number=1):
  """"""
  with tf.io.gfile.GFile(path, "rb") as f:
    data = f.read()
  offset = 0
  max_offset = len(data) - 1
  while offset < max_offset:
    labels = np.frombuffer(data, dtype=np.uint8, count=labels_number,
                           offset=offset).reshape((labels_number,))
    # 1 byte per label, 1024 * 3 = 3072 bytes for the image.
    offset += labels_number
    img = (np.frombuffer(data, dtype=np.uint8, count=3072, offset=offset)
           .reshape((3, _CIFAR_IMAGE_SIZE, _CIFAR_IMAGE_SIZE))
           .transpose((1, 2, 0))
          )
    offset += 3072
    yield labels, img
559017
def as_PIL(self):
        
        if isinstance(self.data, numpy.ndarray):
            if self.data.dtype == numpy.uint8:
                result = PIL.Image.fromarray(self.data)
            else:
                result = PIL.Image.fromarray(
                    self.data.clip(0, 255).astype(numpy.uint8))
        elif isinstance(self.data, PIL.Image.Image):
            result = self.data
        else:
            raise RuntimeError(
                'Cannot convert "%s" to PIL' % self.data.__class__.__name__)
        return result
129037
def _getdata(self, data_source, start=None, end=None):
        """"""
        assert start is not None or end is not None, 'should at least specify start or end'
        start = start if start is not None else 0
        if end is None:
            end = data_source[0][1].shape[0] if data_source else 0
        s = slice(start, end)
        return [
            x[1][s]
            if isinstance(x[1], (np.ndarray, NDArray)) else
            # h5py (only supports indices in increasing order)
            array(x[1][sorted(self.idx[s])][[
                list(self.idx[s]).index(i)
                for i in sorted(self.idx[s])
            ]]) for x in data_source
        ]
448237
function getImagePixels() {
    var w = width;
    var h = height;
    pixels = [];
    var data = image;
    var count = 0;

    for (var i = 0; i < h; i++) {

      for (var j = 0; j < w; j++) {

        var b = (i * w * 4) + j * 4;
        pixels[count++] = data[b];
        pixels[count++] = data[b + 1];
        pixels[count++] = data[b + 2];

      }

    }
  }
832946
def _data(self, cube, weighted, prune):
        """"""
        result = []
        for slice_ in cube.slices:
            if cube.has_mr:
                return self._mr_index(cube, weighted, prune)
            num = slice_.margin(axis=0, weighted=weighted, prune=prune)
            den = slice_.margin(weighted=weighted, prune=prune)
            margin = num / den
            proportions = slice_.proportions(axis=1, weighted=weighted, prune=prune)
            result.append(proportions / margin)

        if len(result) == 1 and cube.ndim < 3:
            result = result[0]
        else:
            if prune:
                mask = np.array([slice_.mask for slice_ in result])
                result = np.ma.masked_array(result, mask)
            else:
                result = np.array(result)

        return result
1047619
def _load_pil_image(self, filename):
        
        self._channel_data = []
        self._original_channel_data = []

        im = Image.open(filename)
        self._image = ImageOps.grayscale(im)
        im.load()

        file_data = np.asarray(im, float)
        file_data = file_data / file_data.max()

        # if the image has more than one channel, load them
        if( len(file_data.shape) == 3 ):
            num_channels = file_data.shape[2]
            for i in range(num_channels):
                self._channel_data.append( file_data[:, :, i])
                self._original_channel_data.append( file_data[:, :, i] )
837953
def get_bytes_to_image_callback(image_dims=(224, 224)):
    """"""
    from keras.preprocessing import image
    import numpy as np
    from PIL import Image
    from io import BytesIO

    def preprocess_image_bytes(data_bytes):
        """Process image bytes for ImageNet."""
        try:
            img = Image.open(BytesIO(data_bytes))  # open image
        except OSError as e:
            raise ValueError('Please provide a raw image')
        img = img.resize(image_dims, Image.ANTIALIAS)  # model requires 224x224 pixels
        x = image.img_to_array(img)  # convert image to numpy array
        x = np.expand_dims(x, axis=0)  # model expects dim 0 to be iterable across images
        return x
    return preprocess_image_bytes
894642
def _fromdata(self, code, dtype, count, value, name=None):
        """"""
        self.code = int(code)
        self.name = name if name else str(code)
        self.dtype = TIFF_DATA_TYPES[dtype]
        self.count = int(count)
        self.value = value
293983
def numpy_to_texture(image):
    """"""
    if not isinstance(image, np.ndarray):
        raise TypeError('Unknown input type ({})'.format(type(image)))
    if image.ndim != 3 or image.shape[2] != 3:
        raise AssertionError('Input image must be nn by nm by RGB')
    grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1))
    grid.point_arrays['Image'] = np.flip(image.swapaxes(0,1), axis=1).reshape((-1, 3), order='F')
    grid.set_active_scalar('Image')
    return image_to_texture(grid)
443076
def _series_mdgel(self):
        """"""
        # only a single page, scaled according to metadata in second page
        self.pages.useframes = False
        self.pages.keyframe = 0
        md = self.mdgel_metadata
        if md['FileTag'] in (2, 128):
            dtype = numpy.dtype('float32')
            scale = md['ScalePixel']
            scale = scale[0] / scale[1]  # rational
            if md['FileTag'] == 2:
                # squary root data format
                def transform(a):
                    return a.astype('float32')**2 * scale
            else:
                def transform(a):
                    return a.astype('float32') * scale
        else:
            transform = None
        page = self.pages[0]
        self.is_uniform = False
        return [TiffPageSeries([page], page.shape, dtype, page.axes,
                               transform=transform, kind='MDGel')]
1063140
def _sumImages(self,numarrayObjectList):
        
        if numarrayObjectList in [None, []]:
            return None

        tsum = np.zeros(numarrayObjectList[0].shape, dtype=numarrayObjectList[0].dtype)

        for image in numarrayObjectList:
            tsum += image

        return tsum
373863
def to_array(self):
        
        array = super(PhotoSize, self).to_array()
        array['file_id'] = u(self.file_id)  # py2: type unicode, py3: type str

        array['width'] = int(self.width)  # type int
        array['height'] = int(self.height)  # type int
        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        return array
463528
def aspage(self):
        """"""
        if self.offset is None:
            raise ValueError('cannot return virtual frame as page.')
        self.parent.filehandle.seek(self.offset)
        return TiffPage(self.parent, index=self.index)