Return an image array from run-length encoded string `mask_rle` with `shape`.
167814
def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask:
    ""
    s = mask_rle.split()
    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
    starts -= 1
    ends = starts + lengths
    img = np.zeros(shape[0]*shape[1], dtype=np.uint)
    for low, up in zip(starts, ends): img[low:up] = 1
    return img.reshape(shape)
1116198
def mdaArray(arry, dtype=numpy.float, mask=None):
    
    a = numpy.array(arry, dtype)
    res = MaskedDistArray(a.shape, a.dtype)
    res[:] = a
    res.mask = mask
    return res
795945
def _extract_mask_distance(image, mask = slice(None), voxelspacing = None):
    
    if isinstance(mask, slice):
        mask = numpy.ones(image.shape, numpy.bool)
    
    distance_map = distance_transform_edt(mask, sampling=voxelspacing)
    
    return _extract_intensities(distance_map, mask)
861632
def _generate_segments(im_orig, scale, sigma, min_size):
    

    # open the Image
    im_mask = skimage.segmentation.felzenszwalb(
        skimage.util.img_as_float(im_orig), scale=scale, sigma=sigma,
        min_size=min_size)

    # merge mask channel to the image as a 4th channel
    im_orig = numpy.append(
        im_orig, numpy.zeros(im_orig.shape[:2])[:, :, numpy.newaxis], axis=2)
    im_orig[:, :, 3] = im_mask

    return im_orig
605373
def guess_mode(self, data):
        
        # TODO: do we want to support dimensions being at the beginning of the array?
        if data.ndim == 2:
            return "L"
        elif data.shape[-1] == 3:
            return "RGB"
        elif data.shape[-1] == 4:
            return "RGBA"
        else:
            raise ValueError(
                "Un-supported shape for image conversion %s" % list(data.shape))
1152179
def crop(im, r, c, sz): 
    '''
     
    '''
    return im[r:r+sz, c:c+sz]
649275
def invert_pixel_mask(mask):
    '''
    '''
    inverted_mask = np.ones(shape=(80, 336), dtype=np.dtype('>u1'))
    inverted_mask[mask >= 1] = 0
    return inverted_mask
934544
def _rhat_ufunc(ary):
    
    target = np.empty(ary.shape[:-2])
    for idx in np.ndindex(target.shape):
        target[idx] = _get_split_rhat(ary[idx])
    return target
537421
def get_mask_from_raster(rasterfile, outmaskfile, keep_nodata=False):
        
        raster_r = RasterUtilClass.read_raster(rasterfile)
        xsize = raster_r.nCols
        ysize = raster_r.nRows
        nodata_value = raster_r.noDataValue
        srs = raster_r.srs
        x_min = raster_r.xMin
        y_max = raster_r.yMax
        dx = raster_r.dx
        data = raster_r.data

        if not keep_nodata:
            i_min = ysize - 1
            i_max = 0
            j_min = xsize - 1
            j_max = 0
            for i in range(ysize):
                for j in range(xsize):
                    if abs(data[i][j] - nodata_value) > DELTA:
                        i_min = min(i, i_min)
                        i_max = max(i, i_max)
                        j_min = min(j, j_min)
                        j_max = max(j, j_max)

            # print(i_min, i_max, j_min, j_max)
            y_size_mask = i_max - i_min + 1
            x_size_mask = j_max - j_min + 1
            x_min_mask = x_min + j_min * dx
            y_max_mask = y_max - i_min * dx
        else:
            y_size_mask = ysize
            x_size_mask = xsize
            x_min_mask = x_min
            y_max_mask = y_max
            i_min = 0
            j_min = 0
        print('%dx%d -> %dx%d' % (xsize, ysize, x_size_mask, y_size_mask))

        mask = numpy.zeros((y_size_mask, x_size_mask))

        for i in range(y_size_mask):
            for j in range(x_size_mask):
                if abs(data[i + i_min][j + j_min] - nodata_value) > DELTA:
                    mask[i][j] = 1
                else:
                    mask[i][j] = DEFAULT_NODATA

        mask_geotrans = [x_min_mask, dx, 0, y_max_mask, 0, -dx]
        RasterUtilClass.write_gtiff_file(outmaskfile, y_size_mask, x_size_mask, mask,
                                         mask_geotrans, srs, DEFAULT_NODATA, GDT_Int32)
        return Raster(y_size_mask, x_size_mask, mask, DEFAULT_NODATA, mask_geotrans, srs)
934370
def mask(mask_key, data):
        
        if data is None:
            data = ""

        if isinstance(mask_key, six.text_type):
            mask_key = six.b(mask_key)

        if isinstance(data, six.text_type):
            data = six.b(data)

        if numpy:
            origlen = len(data)
            _mask_key = mask_key[3] << 24 | mask_key[2] << 16 | mask_key[1] << 8 | mask_key[0]

            # We need data to be a multiple of four...
            data += bytes(" " * (4 - (len(data) % 4)), "us-ascii")
            a = numpy.frombuffer(data, dtype="uint32")
            masked = numpy.bitwise_xor(a, [_mask_key]).astype("uint32")
            if len(data) > origlen:
              return masked.tobytes()[:origlen]
            return masked.tobytes()
        else:
            _m = array.array("B", mask_key)
            _d = array.array("B", data)
            return _mask(_m, _d)
314054
def thin(image, mask=None, iterations=1):
    '''
    '''
    global thin_table, eight_connect
    if thin_table is None:
        thin_table = np.zeros((2,512),bool)
        for i in range(512):
            if (i & 16) == 0:
                # All zeros -> 0
                continue
            pat = pattern_of(i & ~ 16)
            ipat = pat.astype(int)
            if scind.label(pat, eight_connect)[1] != 1:
                thin_table[:,i] = True
                continue
            n1 = ((ipat[0,0] or ipat[0,1]) + (ipat[0,2] or ipat[1,2])+
                  (ipat[2,2] or ipat[2,1]) + (ipat[2,0] or ipat[1,0]))
            n2 = ((ipat[0,1] or ipat[0,2]) + (ipat[1,2] or ipat[2,2])+
                  (ipat[2,1] or ipat[2,0]) + (ipat[1,0] or ipat[0,0]))
            if min(n1,n2) not in (2,3):
                thin_table[:,i] = True
                continue
            thin_table[0,i] = ((pat[0,1] or pat[0,2] or not pat[2,2]) and 
                               pat[1,2])
            thin_table[1,i] = ((pat[2,1] or pat[2,0] or not pat[0,0]) and
                               pat[1,0])
    if mask is None:
        masked_image = image.copy()
    else:
        masked_image = image.copy()
        masked_image[~mask] = False
    index_i, index_j, masked_image = prepare_for_index_lookup(masked_image, False)
    if iterations is None:
        iterations = len(index_i)
    for i in range(iterations):
        hit_count = len(index_i)
        for j in range(2):
            index_i, index_j, = index_lookup(index_i, index_j, 
                                             masked_image,
                                             thin_table[j], 1)
        if hit_count == len(index_i):
            break
    masked_image = extract_from_image_lookup(image, index_i, index_j)
    if not mask is None:
        masked_image[~mask] = masked_image[~mask]
    return masked_image
1210025
def slices(img, shape=[3, 4]):
    
    sh = np.asarray(shape)
    i_max = np.prod(sh)
    allimg = np.zeros(img.shape[-2:] * sh)

    for i in range(0, i_max):
        # i = 0
        islice = round((img.shape[0] / float(i_max)) * i)
        #         print(islice)
        imgi = img[islice, :, :]
        coords = index_to_coords(i, sh)
        aic = np.asarray(img.shape[-2:]) * coords

        allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi

    #     plt.imshow(imgi)
    #     print(imgi.shape)
    #     print(img.shape)
    return allimg
217890
def _strslices(self):
        """"""
        pad = self.padding or 0
        for sli in self.slices():
            if sli.start + 1 == sli.stop:
                yield "%0*d" % (pad, sli.start)
            else:
                assert sli.step >= 0, "Internal error: sli.step < 0"
                if sli.step == 1:
                    yield "%0*d-%0*d" % (pad, sli.start, pad, sli.stop - 1)
                else:
                    yield "%0*d-%0*d/%d" % (pad, sli.start, pad, sli.stop - 1, \
                                            sli.step)
1230509
def annToMask(self, ann):
        
        rle = self.annToRLE(ann)
        m = maskUtils.decode(rle)
        return m
868863
def diag(image, mask=None, iterations=1):
    '''
    
    '''
    global diag_table
    if mask is None:
        masked_image = image
    else:
        masked_image = image.astype(bool).copy()
        masked_image[~mask] = False
    result = table_lookup(masked_image, diag_table, False, iterations)
    if not mask is None:
        result[~mask] = image[~mask]
    return result
317876
def _extract_mnist_images(filename, num_images):
  
  with gzip.open(filename) as bytestream:
    bytestream.read(16)
    buf = bytestream.read(_MNIST_IMAGE_SIZE * _MNIST_IMAGE_SIZE * num_images)
    data = np.frombuffer(buf, dtype=np.uint8)
    data = data.reshape(num_images, _MNIST_IMAGE_SIZE, _MNIST_IMAGE_SIZE, 1)
  return data
146000
def convert_mask_to_pil(mask, real=True):
    """"""
    from PIL import Image
    header = mask._layer._psd._record.header
    channel_ids = [ci.id for ci in mask._layer._record.channel_info]
    if real and mask._has_real():
        width = mask._data.real_right - mask._data.real_left
        height = mask._data.real_bottom - mask._data.real_top
        channel = mask._layer._channels[
            channel_ids.index(ChannelID.REAL_USER_LAYER_MASK)
        ]
    else:
        width = mask._data.right - mask._data.left
        height = mask._data.bottom - mask._data.top
        channel = mask._layer._channels[
            channel_ids.index(ChannelID.USER_LAYER_MASK)
        ]
    data = channel.get_data(width, height, header.depth, header.version)
    return _create_channel((width, height), data, header.depth)