Cut out `n_holes` number of square holes of size `length` in image at random locations.
485778
def _cutout(x, n_holes:uniform_int=1, length:uniform_int=40):
    ""
    h,w = x.shape[1:]
    for n in range(n_holes):
        h_y = np.random.randint(0, h)
        h_x = np.random.randint(0, w)
        y1 = int(np.clip(h_y - length / 2, 0, h))
        y2 = int(np.clip(h_y + length / 2, 0, h))
        x1 = int(np.clip(h_x - length / 2, 0, w))
        x2 = int(np.clip(h_x + length / 2, 0, w))
        x[:, y1:y2, x1:x2] = 0
    return x
985752
def clip(self, px, py, w, h, img):
        ''''''
        sx = 0
        sy = 0

        if px < 0:
            sx = -px
            w += px
            px = 0
        if py < 0:
            sy = -py
            h += py
            py = 0
        if px+w > img.width:
            w = img.width - px
        if py+h > img.height:
            h = img.height - py
        return (px, py, sx, sy, w, h)
1014983
static function cut($pic, $dst_pic, $width, $height = null, $qulitity = 100)
    {
        $im = imagecreatefromjpeg($pic);

        if (imagesx($im) > $width)
        {
            $old_w = imagesx($im);
            $old_h = imagesy($im);

            if ($height == null)
            {
                $w_h = $old_w / $old_h;
                $height = $width * $w_h;
            }

            $newim = imagecreatetruecolor($width, $height);
            imagecopyresampled($newim, $im, 0, 0, 0, 0, $width, $height, $old_w, $old_h);
            imagejpeg($newim, $dst_pic, $qulitity);
            imagedestroy($im);

            return true;
        }
        elseif ($pic != $dst_pic)
        {
            return copy($pic, $dst_pic);
        }

        return false;
    }
1122479
def enhance_dark_holes(image, min_radius, max_radius, mask=None):
    '''
    '''
    #
    # Do 4-connected erosion
    #
    se = np.array([[False, True, False],
                   [True, True, True],
                   [False, True, False]])
    #
    # Invert the intensities
    #
    inverted_image = image.max() - image
    previous_reconstructed_image = inverted_image
    eroded_image = inverted_image
    smoothed_image = np.zeros(image.shape)
    for i in range(max_radius+1):
        eroded_image = grey_erosion(eroded_image, mask=mask, footprint = se)
        reconstructed_image = grey_reconstruction(eroded_image, inverted_image,
                                                  footprint = se)
        output_image = previous_reconstructed_image - reconstructed_image
        if i >= min_radius:
            smoothed_image = np.maximum(smoothed_image,output_image)
        previous_reconstructed_image = reconstructed_image
    return smoothed_image
1242795
def make_data(n,width):
    """"""
    x = dict([(i,100*random.random()) for i in range(1,n+1)])
    y = dict([(i,100*random.random()) for i in range(1,n+1)])
    c = {}
    for i in range(1,n+1):
        for j in range(1,n+1):
            if j != i:
                c[i,j] = distance(x[i],y[i],x[j],y[j])

    e = {1:0}
    l = {1:0}
    start = 0
    delta = int(76.*math.sqrt(n)/n * width)+1
    for i in range(1,n):
        j = i+1
        start += c[i,j]
        e[j] = max(start-delta,0)
        l[j] = start + delta

    return c,x,y,e,l
277605
def rand_resize_crop(size:int, max_scale:float=2., ratios:Tuple[float,float]=(0.75,1.33)):
    ""
    return [zoom_squish(scale=(1.,max_scale,8), squish=(*ratios,8), invert=(0.5,8), row_pct=(0.,1.), col_pct=(0.,1.)),
            crop(size=size)]
485799
def make_list(args):
    
    image_list = list_image(args.root, args.recursive, args.exts)
    image_list = list(image_list)
    if args.shuffle is True:
        random.seed(100)
        random.shuffle(image_list)
    N = len(image_list)
    chunk_size = (N + args.chunks - 1) // args.chunks
    for i in range(args.chunks):
        chunk = image_list[i * chunk_size:(i + 1) * chunk_size]
        if args.chunks > 1:
            str_chunk = '_%d' % i
        else:
            str_chunk = ''
        sep = int(chunk_size * args.train_ratio)
        sep_test = int(chunk_size * args.test_ratio)
        if args.train_ratio == 1.0:
            write_list(args.prefix + str_chunk + '.lst', chunk)
        else:
            if args.test_ratio:
                write_list(args.prefix + str_chunk + '_test.lst', chunk[:sep_test])
            if args.train_ratio + args.test_ratio < 1.0:
                write_list(args.prefix + str_chunk + '_val.lst', chunk[sep_test + sep:])
            write_list(args.prefix + str_chunk + '_train.lst', chunk[sep_test:sep_test + sep])
627690
def crop_coords(img, padding):
    """"""

    coords = np.nonzero(img)
    empty_axis_exists = np.any([len(arr) == 0 for arr in coords])
    if empty_axis_exists:
        end_coords = img.shape
        beg_coords = np.zeros((1, img.ndim)).astype(int).flatten()
    else:
        min_coords = np.array([arr.min() for arr in coords])
        max_coords = np.array([arr.max() for arr in coords])
        beg_coords = np.fmax(0, min_coords - padding)
        end_coords = np.fmin(img.shape, max_coords + padding)

    return beg_coords, end_coords
21776
def _image_of_size(image_size):
  """"""
  return np.random.uniform(0, 256, [image_size, image_size, 3]).astype(np.uint8)
378328
def crop_square(im, r, c, sz):
    '''
    
    '''
    return im[r:r+sz, c:c+sz]
776551
def imscatter(images, positions):
    '''
        
    '''
    positions = np.array(positions)

    bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images])
    tops = bottoms + np.array([im.shape[1] for im in images])

    lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images])
    rigths = lefts + np.array([im.shape[0] for im in images])

    most_bottom = int(np.floor(bottoms.min()))
    most_top = int(np.ceil(tops.max()))

    most_left = int(np.floor(lefts.min()))
    most_right = int(np.ceil(rigths.max()))

    scatter_image = np.zeros(
        [most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype)

    # shift, now all from zero
    positions -= [most_left, most_bottom]

    for im, pos in zip(images, positions):

        xl = int(pos[0] - im.shape[0] / 2)
        xr = xl + im.shape[0]

        yb = int(pos[1] - im.shape[1] / 2)
        yt = yb + im.shape[1]

        scatter_image[xl:xr, yb:yt, :] = im
    return scatter_image
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
594047
def random_pairs_with_replacement(n, shape, random_state=None):
    """"""

    if not isinstance(random_state, np.random.RandomState):
        random_state = np.random.RandomState(random_state)

    n_max = max_pairs(shape)

    if n_max <= 0:
        raise ValueError('n_max must be larger than 0')

    # make random pairs
    indices = random_state.randint(0, n_max, n)

    if len(shape) == 1:
        return _map_tril_1d_on_2d(indices, shape[0])
    else:
        return np.unravel_index(indices, shape)
1093729
def cleanup(arg):
    """"""
    arg = numpy.asarray(arg)
    if len(arg.shape) <= 1:
        arg = arg.reshape(arg.size, 1)
    elif len(arg.shape) > 2:
        raise ValueError("shapes must be smaller than 3")
    return arg
509935
def _random_crop(image, size):
  """"""
  bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
  random_image, bbox = distorted_bounding_box_crop(
      image,
      bbox,
      min_object_covered=0.1,
      aspect_ratio_range=(3. / 4, 4. / 3.),
      area_range=(0.08, 1.0),
      max_attempts=1,
      scope=None)
  bad = _at_least_x_are_true(tf.shape(image), tf.shape(random_image), 3)

  image = tf.cond(
      bad, lambda: _center_crop(_do_scale(image, size), size),
      lambda: tf.image.resize_bicubic([random_image], [size, size])[0])
  return image
385328
def __cutRaw(self, oiraw, maxLength):
        ''''''
        vec = []
        m = re.findall(u".*?[。？！；;!?]", oiraw)
        num, l, last = 0, 0, 0
        for i in range(len(m)):
            if(num + len(m[i]) >= maxLength):
                vec.append("".join(m[last:i]))
                last = i
                num = len(m[i])
            else:
                num += len(m[i])
            l += len(m[i])
        if(len(oiraw)-l + num >= maxLength):
            vec.append("".join(m[last:len(m)]))
            vec.append(oiraw[l:])
        else:
            vec.append(oiraw[l-num:])
        return vec
273137
def removeSinglePixels(img):
    '''
    
    '''

    gx = img.shape[0]
    gy = img.shape[1]

    for i in range(gx):
        for j in range(gy):

            if img[i, j]:

                found_neighbour = False
                for ii in range(max(0, i - 1), min(gx, i + 2)):
                    for jj in range(max(0, j - 1), min(gy, j + 2)):

                        if ii == i and jj == j:
                            continue

                        if img[ii, jj]:
                            found_neighbour = True
                            break
                    if found_neighbour:
                        break

                if not found_neighbour:
                    img[i, j] = 0