Slice an image into parts slice_size tall.
767976
def _long_image_slice(in_filepath, out_filepath, slice_size):
    
    print 'slicing image: {0}'.format(in_filepath)
    img = Image.open(in_filepath)
    width, height = img.size
    upper = 0
    left = 0
    slices = int(math.ceil(height / slice_size))

    count = 1
    for slice in range(slices):
        # if we are at the end, set the lower bound to be the bottom of the image
        if count == slices:
            lower = height
        else:
            lower = int(count * slice_size)
        # set the bounding box! The important bit
        bbox = (left, upper, width, lower)
        working_slice = img.crop(bbox)
        upper += slice_size
        # save the slice
        new_filepath = _build_sliced_filepath(out_filepath, count)
        working_slice.save(new_filepath)
        count += 1
1021332
def slice_create(center, block, start=0, stop=None):
    ''''''

    do = coor_to_pix_1d(center - block)
    up = coor_to_pix_1d(center + block)

    l = max(start, do)

    if stop is not None:
        h = min(up + 1, stop)
    else:
        h = up + 1

    return slice(l, h, 1)
142475
def pick_slices(img, num_slices_per_view):
    

    slices = list()
    for view in range(len(img.shape)):
        dim_size = img.shape[view]
        non_empty_slices = np.array(
            [sl for sl in range(dim_size) if np.count_nonzero(get_axis(img, view, sl)) > 0])
        num_non_empty = len(non_empty_slices)

        # trying to 5% slices at the tails (bottom clipping at 0)
        skip_count = max(0, np.around(num_non_empty * 0.05).astype('int16'))
        # only when possible
        if skip_count > 0 and (num_non_empty - 2 * skip_count >= num_slices_per_view):
            non_empty_slices = non_empty_slices[skip_count: -skip_count]
            num_non_empty = len(non_empty_slices)

        # sampling non-empty slices only
        sampled_indices = np.linspace(0, num_non_empty, num=min(num_non_empty, num_slices_per_view),
                                      endpoint=False)
        slices_in_dim = non_empty_slices[np.around(sampled_indices).astype('int64')]

        # ensure you do not overshoot
        slices_in_dim = [sn for sn in slices_in_dim if sn >= 0 or sn <= num_non_empty]

        slices.append(slices_in_dim)

    return slices
173448
def slice_into_pieces(seq, n):
    """"""
    length = len(seq)
    if length % n == 0:
        size = length // n
    else:
        size = length // n + 1
    for it in slice_by_size(seq, size):
        yield it
534083
def to_rectangular(image):
    
    # xy image, vertical scaled to 360 degrees
    xy = pyvips.Image.xyz(image.width, image.height)
    xy *= [1, 360.0 / image.height]

    index = xy.rect()

    # scale to image rect
    scale = min(image.width, image.height) / float(image.width)
    index *= scale / 2.0
    index += [image.width / 2.0, image.height / 2.0]

    return image.mapim(index)
561803
def crop_3dimage(img, beg_coords, end_coords):
    """"""

    cropped_img = img[
                  beg_coords[0]:end_coords[0],
                  beg_coords[1]:end_coords[1],
                  beg_coords[2]:end_coords[2]
                  ]

    return cropped_img
366506
def pieces(array, chunk_size):
        """"""
        for i in range(0, len(array), chunk_size): yield array[i:i+chunk_size]
799144
def cut_edges(image, numPix):
    
    nx, ny = image.shape
    if nx < numPix or ny < numPix:
        print('WARNING: image can not be resized, in routine cut_edges.')
        return image
    if nx % 2 == 0 or ny % 2 == 0 or numPix % 2 == 0:
        #pass
        print("WARNING: image or cutout side are even number. This routine only works for odd numbers %s %s %s"
                         % (nx, ny, numPix))
    cx = int((nx-1)/2)
    cy = int((ny-1)/2)
    d = int((numPix-1)/2)
    if nx % 2 == 0:
        cx += 1
    if ny % 2 == 0:
        cy += 1
    resized = image[cx-d:cx+d+1, cy-d:cy+d+1]
    return copy.deepcopy(resized)
784393
def _read_image_slice(self, arg):
        
        if 'ndims' not in self._info:
            raise ValueError("Attempt to slice empty extension")

        if isinstance(arg, slice):
            # one-dimensional, e.g. 2:20
            return self._read_image_slice((arg,))

        if not isinstance(arg, tuple):
            raise ValueError("arguments must be slices, one for each "
                             "dimension, e.g. [2:5] or [2:5,8:25] etc.")

        # should be a tuple of slices, one for each dimension
        # e.g. [2:3, 8:100]
        nd = len(arg)
        if nd != self._info['ndims']:
            raise ValueError("Got slice dimensions %d, "
                             "expected %d" % (nd, self._info['ndims']))

        targ = arg
        arg = []
        for a in targ:
            if isinstance(a, slice):
                arg.append(a)
            elif isinstance(a, int):
                arg.append(slice(a, a+1, 1))
            else:
                raise ValueError("arguments must be slices, e.g. 2:12")

        dims = self._info['dims']
        arrdims = []
        first = []
        last = []
        steps = []

        # check the args and reverse dimensions since
        # fits is backwards from numpy
        dim = 0
        for slc in arg:
            start = slc.start
            stop = slc.stop
            step = slc.step

            if start is None:
                start = 0
            if stop is None:
                stop = dims[dim]
            if step is None:
                step = 1
            if step < 1:
                raise ValueError("slice steps must be >= 1")

            if start < 0:
                start = dims[dim] + start
                if start < 0:
                    raise IndexError("Index out of bounds")

            if stop < 0:
                stop = dims[dim] + start + 1

            # move to 1-offset
            start = start + 1

            if stop < start:
                raise ValueError("python slices but include at least one "
                                 "element, got %s" % slc)
            if stop > dims[dim]:
                stop = dims[dim]

            first.append(start)
            last.append(stop)
            steps.append(step)
            arrdims.append(stop-start+1)

            dim += 1

        first.reverse()
        last.reverse()
        steps.reverse()
        first = numpy.array(first, dtype='i8')
        last = numpy.array(last, dtype='i8')
        steps = numpy.array(steps, dtype='i8')

        npy_dtype = self._get_image_numpy_dtype()
        array = numpy.zeros(arrdims, dtype=npy_dtype)
        self._FITS.read_image_slice(self._ext+1, first, last, steps, array)
        return array
700064
def from_image(cls, image, partname):
        
        return ImagePart(partname, image.content_type, image.blob, image)
1323422
def getbyteslice(self, start, end):
        """"""
        c = self._rawarray[start:end]
        return c
23471
def crop_2dimage(img, beg_coords, end_coords):
    """"""

    cropped_img = img[
                  beg_coords[0]:end_coords[0],
                  beg_coords[1]:end_coords[1],
                  ]

    return cropped_img
1095457
def get_X_slice(self, rmind):
        ''''''
        if self.forest.optimize_memory_use:
            return self.forest.X[:, rmind][self.subsample]
        else:
            return self.X[:, rmind]
1160829
def slice_on_length(self, data_len, *addSlices):
        '''
        
        '''
        if len(self.ordered_ranges) + len(addSlices) == 0:
            return slice(None,None,None)
        ranges = self.ordered_ranges
        if len(addSlices) > 0:
            ranges = ranges + DimensionRange(*addSlices).ordered_ranges
        return self._combine_lists_of_ranges_on_length(data_len, *ranges)
698207
def _scaleTo8bit(self, img):
        '''
        
        '''
        r = scaleSignalCutParams(img, 0.02)  # , nSigma=3)
        self.signal_ranges.append(r)
        return toUIntArray(img, dtype=np.uint8, range=r)
337266
def _slice(self, start, end):
        """"""
        if end == start:
            return self.__class__()
        offset = self._offset
        startbyte, newoffset = divmod(start + offset, 8)
        endbyte = (end + offset - 1) // 8
        bs = self.__class__()
        bs._setbytes_unsafe(self._datastore.getbyteslice(startbyte, endbyte + 1), end - start, newoffset)
        return bs
336206
def parse_size(image, size):
        
        bits = size.split("x")
        if image.size[0] == 0 or image.size[1] == 0:
            ratio = 1.0
        else:
            ratio = float(image.size[0]) / float(image.size[1])

        if len(bits) == 1 or not bits[1]:
            width = int(bits[0])
            height = int(1 / ratio * width)
        elif not bits[0]:
            height = int(bits[1])
            width = int(height * ratio)
        else:
            width, height = map(int, bits)
        return width, height