Draw mask contour on a pillow image.
162886
def _draw_contour(self, img):
        """"""
        if self.mask is None or self.contour_width == 0:
            return img

        mask = self._get_bolean_mask(self.mask) * 255
        contour = Image.fromarray(mask.astype(np.uint8))
        contour = contour.resize(img.size)
        contour = contour.filter(ImageFilter.FIND_EDGES)
        contour = np.array(contour)

        # make sure borders are not drawn before changing width
        contour[[0, -1], :] = 0
        contour[:, [0, -1]] = 0

        # use gaussian to change width, divide by 10 to give more resolution
        radius = self.contour_width / 10
        contour = Image.fromarray(contour)
        contour = contour.filter(ImageFilter.GaussianBlur(radius=radius))
        contour = np.array(contour) > 0
        contour = np.dstack((contour, contour, contour))

        # color the contour
        ret = np.array(img) * np.invert(contour)
        if self.contour_color != 'black':
            color = Image.new(img.mode, img.size, self.contour_color)
            ret += np.array(color) * contour

        return Image.fromarray(ret)
358244
def set_moving_mask(self, image):
        
        if not isinstance(image, iio.ANTsImage):
            raise ValueError('image must be ANTsImage type')

        if image.dimension != self.dimension:
            raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension))

        self._metric.setMovingImage(image.pointer, True)
        self.moving_mask = image
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)
243337
def plot_mask_cell(true_mask,
                   predicted_mask,
                   cell,
                   suffix,
                   ax1,
                   ax2,
                   ax3,
                   padding=16):
    """"""
    for ax in [ax1, ax2, ax3]:
        ax.grid(False)
        ax.set_xticks([])
        ax.set_yticks([])
    ax1.imshow(true_mask[padding:-padding, padding:-padding], cmap='viridis')
    ax1.set_title('True Mask - {}'.format(suffix))
    ax2.imshow(
        predicted_mask[padding:-padding, padding:-padding], cmap='viridis')
    ax2.set_title('Predicted Mask - {}'.format(suffix))
    ax3.imshow(convert_cell_to_img(cell, padding=padding))
    ax3.set_title('Image - {}'.format(suffix))
    return ax1, ax2, ax3
140768
def _drawLine(self, image):
        """"""
        w, h = image.size
        w *= 5
        h *= 5

        l_image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
        l_draw = ImageDraw.Draw(l_image)

        x1 = int(w * random.uniform(0, 0.1))
        y1 = int(h * random.uniform(0, 1))
        x2 = int(w * random.uniform(0.9, 1))
        y2 = int(h * random.uniform(0, 1))

        # Line width modifier was chosen as an educated guess
        # based on default image area.
        l_width = round((w * h)**0.5 * 2.284e-2)

        # Draw
        l_draw.line(((x1, y1), (x2, y2)), fill=(0, 0, 0, 255), width=l_width)

        # Transform
        l_image = self._rndLineTransform(l_image)
        l_image = l_image.resize(image.size, resample=self.resample)

        # Paste onto image
        image.paste(l_image, (0, 0), l_image)
1194256
def _draw_image(self, ci):
        
        img = img_adjust(ci.image, ci.opacity, tempdir=self.dir)
        self.can.drawImage(img, x=ci.x, y=ci.y, width=ci.w, height=ci.h, mask=ci.mask,
                           preserveAspectRatio=ci.preserve_aspect_ratio, anchorAtXY=True)
695600
def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
    
    r,c,*_ = im.shape
    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)
794716
function mask (contrast) {
	var a = Math.pow(392.498 * contrast, 0.7);
	var b = Math.pow(0.0153 * a, 4.0);
	return Math.pow(1.0 + b, 0.25);
}
21306
def shift_to_coords(self, pix, fill_value=np.nan):
        """"""

        pix_offset = self.get_offsets(pix)
        dpix = np.zeros(len(self.shape) - 1)
        for i in range(len(self.shape) - 1):
            x = self.rebin * (pix[i] - pix_offset[i + 1]
                              ) + (self.rebin - 1.0) / 2.
            dpix[i] = x - self._pix_ref[i]

        pos = [pix_offset[i] + self.shape[i] // 2
               for i in range(self.data.ndim)]
        s0, s1 = utils.overlap_slices(self.shape_out, self.shape, pos)

        k = np.zeros(self.data.shape)
        for i in range(k.shape[0]):
            k[i] = shift(self._data_spline[i], dpix, cval=np.nan,
                         order=2, prefilter=False)

        for i in range(1, len(self.shape)):
            k = utils.sum_bins(k, i, self.rebin)

        k0 = np.ones(self.shape_out) * fill_value

        if k[s1].size == 0 or k0[s0].size == 0:
            return k0
        k0[s0] = k[s1]
        return k0
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
1373339
def fill(image, mask=None, iterations=1):
    '''
    '''
    global fill_table
    if mask is None:
        masked_image = image
    else:
        masked_image = image.astype(bool).copy()
        masked_image[~mask] = True
    result = table_lookup(masked_image, fill_table, True, iterations)
    if not mask is None:
        result[~mask] = image[~mask]
    return result
379111
def open_mask(fn:PathOrStr, div=False, convert_mode='L', after_open:Callable=None)->ImageSegment:
    ""
    return open_image(fn, div=div, convert_mode=convert_mode, cls=ImageSegment, after_open=after_open)
1313289
def _set_roi_mask(self, roi_mask):
        """"""

        if isinstance(roi_mask,
                      np.ndarray):  # not (roi_mask is None or roi_mask=='auto'):
            self._verify_shape_compatibility(roi_mask, 'ROI set')
            self.roi_mask = roi_mask

            self.roi_list = np.unique(roi_mask.flatten())
            np.setdiff1d(self.roi_list, cfg.background_value)
        else:
            self.roi_mask = np.ones(self.carpet.shape[:-1]) # last dim is self.fixed_dim already
            self.roi_list = [1, ]
779216
def draw(self, img, pixmapper, bounds):
        ''''''
        if self.hidden:
            return
        thumb = self.img()
        (px,py) = pixmapper(self.latlon)

        # find top left
        (w, h) = image_shape(thumb)
        px -= w//2
        py -= h//2

        (px, py, sx, sy, w, h) = self.clip(px, py, w, h, img)

        thumb_roi = thumb[sy:sy+h, sx:sx+w]
        img[py:py+h, px:px+w] = thumb_roi

        # remember where we placed it for clicked()
        self.posx = px+w//2
        self.posy = py+h//2
419406
def step(self):
        """"""
        # Assign attributes to local variables for convenience.
        u = self._u
        gI = self._data
        dgI = self._ddata
        theta = self._theta
        v = self._v
        
        if u is None:
            raise ValueError("the levelset is not set (use set_levelset)")
        
        res = np.copy(u)
        
        # Balloon.
        if v > 0:
            aux = binary_dilation(u, self.structure)
        elif v < 0:
            aux = binary_erosion(u, self.structure)
        if v!= 0:
            res[self._threshold_mask_v] = aux[self._threshold_mask_v]
        
        # Image attachment.
        aux = np.zeros_like(res)
        dres = np.gradient(res)
        for el1, el2 in zip(dgI, dres):
            aux += el1*el2
        res[aux > 0] = 1
        res[aux < 0] = 0
        
        # Smoothing.
        for i in range(self.smoothing):
            res = curvop(res)
        
        self._u = res
219445
def _to_image_partial_overlap(self, image):
        

        # find the overlap of the mask on the output image shape
        slices_large, slices_small = self._overlap_slices(image.shape)

        if slices_small is None:
            return None    # no overlap

        # insert the mask into the output image
        image[slices_large] = self.data[slices_small]

        return image
210335
def fill(self, background_shape, img):
        
        background_shape = tuple(background_shape)
        return self._fill(background_shape, img)