create mask over the whole image or over the threshold area
498479
def create_mask(
        fnii,
        fimout = '',
        outpath = '',
        fill = 1,
        dtype_fill = np.uint8,
        
        thrsh = 0.,
        fwhm = 0.,):

    ''' '''
    

    #> output path
    if outpath=='' and fimout!='':
        opth = os.path.dirname(fimout)
        if opth=='':
            opth = os.path.dirname(fnii)
            fimout = os.path.join(opth, fimout)

    elif outpath=='':
        opth = os.path.dirname(fnii)

    else:
        opth = outpath

    #> output file name if not given
    if fimout=='':
        fniis = os.path.split(fnii)
        fimout = os.path.join(opth, fniis[1].split('.nii')[0]+'_mask.nii.gz')

    niidct = imio.getnii(fnii, output='all')
    im = niidct['im']
    hdr = niidct['hdr']

    if im.ndim>3:
        raise ValueError('The masking function only accepts 3-D images.')

    #> generate output image
    if thrsh>0.:
        smoim = ndi.filters.gaussian_filter(
                    im,
                    imio.fwhm2sig(fwhm, voxsize=abs(hdr['pixdim'][1])), 
                    mode='mirror')
        thrsh = thrsh*smoim.max()
        immsk = np.int8(smoim>thrsh)
        immsk = imfill(immsk)

        #> output image
        imo = fill * immsk.astype(dtype_fill)

    else:

        imo = fill * np.ones(im.shape, dtype = dtype_fill)

    #> save output image
    imio.array2nii( 
                imo,
                niidct['affine'],
                fimout,
                trnsp = (niidct['transpose'].index(0),
                         niidct['transpose'].index(1),
                         niidct['transpose'].index(2)),
                flip = niidct['flip'])

    return {'fim':fimout, 'im':imo}
539393
def maskAt(self, index):
        
        if isinstance(self.mask, bool):
            return self.mask
        else:
            return self.mask[index]
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
1073999
def _apply_mask(self,p,mat):
        """"""
        mask = p.mask
        ms=p.mask_shape
        if ms is not None:
            mask = ms(x=p.x+p.size*(ms.x*np.cos(p.orientation)-ms.y*np.sin(p.orientation)),
                      y=p.y+p.size*(ms.x*np.sin(p.orientation)+ms.y*np.cos(p.orientation)),
                      orientation=ms.orientation+p.orientation,size=ms.size*p.size,
                      bounds=p.bounds,ydensity=p.ydensity,xdensity=p.xdensity)
        if mask is not None:
            mat*=mask
1042886
private static void thresholdBlock(byte[] luminances,
                                     int xoffset,
                                     int yoffset,
                                     int threshold,
                                     int stride,
                                     BitMatrix matrix) {
    for (int y = 0, offset = yoffset * stride + xoffset; y < BLOCK_SIZE; y++, offset += stride) {
      for (int x = 0; x < BLOCK_SIZE; x++) {
        // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
        if ((luminances[offset + x] & 0xFF) <= threshold) {
          matrix.set(xoffset + x, yoffset + y);
        }
      }
    }
  }
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, ]
1222242
def blit(self, image, x, y):
        """"""
        # adjust the position with the local bbox
        x += self.font_bbox[2] - self.bbox[2]
        y += self.font_bbox[3] - self.bbox[3]
        x += self.font_bbox[0] - self.bbox[0]
        y += self.font_bbox[1] - self.bbox[1]
        image[y:y+self.height, x:x+self.width] = self.bitmap * 255
379808
def mask(self):
        
        if not hasattr(self, "_mask"):
            self._mask = Mask(self) if self.has_mask() else None
        return self._mask
114218
def set_on_mask(self, mask):
        """"""
        set_cmd = self._create_set_property_msg('_on_mask', 0x02, mask)
        self._send_method(set_cmd, self._property_set)
911155
def _apply_mask(
    data: np.ndarray,
    encoded_fill_values: list,
    decoded_fill_value: Any,
    dtype: Any,
) -> np.ndarray:
    """"""
    data = np.asarray(data, dtype=dtype)
    condition = False
    for fv in encoded_fill_values:
        condition |= data == fv
    return np.where(condition, decoded_fill_value, data)
896748
function mask( obj ){
	if ( Object.create ){
		var T = function Masked(){};

		T.prototype = obj;

		return new T();
	}else{
		return Object.create( obj );
	}
}
1034059
def mask(color1 = nil)
      color1 = color1 || Color.from_rgb(255,255,255)
      color2 = color1.dup
      color2.a = 0

      color_replace(color1,color2)
    end
600779
def mask_unphysical(self, data):
        """"""
        if not self.valid_range:
            return data
        else:
            return np.ma.masked_outside(data, np.min(self.valid_range),
                                        np.max(self.valid_range))
927339
def default_mask(mask_arg)
      mask = mask_arg.dup
      mask[:width] = image_file_width if mask[:width].zero?
      mask[:height] = image_file_height if mask[:height].zero?

      crop_size = size_when_fitting({width: image_file_width, height: image_file_height}, mask)
      top_left = get_top_left_crop_corner(crop_size)

      point_and_mask_to_points(top_left, crop_size)
    end
1037316
def set_mask(self, context_len, context):
        

        if self.batch_first:
            max_len = context.size(1)
        else:
            max_len = context.size(0)

        indices = torch.arange(0, max_len, dtype=torch.int64,
                               device=context.device)
        self.mask = indices >= (context_len.unsqueeze(1))
890497
def contour_mask(self, contour):
        
        # fill in new data
        new_data = np.zeros(self.data.shape)
        num_boundary = contour.boundary_pixels.shape[0]
        boundary_px_ij_swapped = np.zeros([num_boundary, 1, 2])
        boundary_px_ij_swapped[:, 0, 0] = contour.boundary_pixels[:, 1]
        boundary_px_ij_swapped[:, 0, 1] = contour.boundary_pixels[:, 0]
        cv2.fillPoly(
            new_data, pts=[
                boundary_px_ij_swapped.astype(
                    np.int32)], color=(
                BINARY_IM_MAX_VAL, BINARY_IM_MAX_VAL, BINARY_IM_MAX_VAL))
        orig_zeros = np.where(self.data == 0)
        new_data[orig_zeros[0], orig_zeros[1]] = 0
        return BinaryImage(new_data.astype(np.uint8), frame=self._frame)
793873
def fixpix2(data, mask, iterations=3, out=None):
    
    out = out if out is not None else data.copy()

    # A binary mask, regions are ones
    binry = mask != 0

    # Label regions in the binary mask
    lblarr, labl = ndimage.label(binry)

    # Structure for dilation is 8-way
    stct = ndimage.generate_binary_structure(2, 2)
    # Pixels in the background
    back = lblarr == 0
    # For each object
    for idx in range(1, labl + 1):
        # Pixels of the object
        segm = lblarr == idx
        # Pixels of the object or the background
        # dilation will only touch these pixels
        dilmask = numpy.logical_or(back, segm)
        # Dilation 3 times
        more = ndimage.binary_dilation(segm, stct,
                                       iterations=iterations,
                                       mask=dilmask)
        # Border pixels
        # Pixels in the border around the object are
        # more and (not segm)
        border = numpy.logical_and(more, numpy.logical_not(segm))
        # Pixels in the border
        xi, yi = border.nonzero()
        # Bilinear leastsq calculator
        calc = FitOne(xi, yi, out[xi, yi])
        # Pixels in the region
        xi, yi = segm.nonzero()
        # Value is obtained from the fit
        out[segm] = calc(xi, yi)

    return out