Set Fixed ANTsImage Mask for metric
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
1252798
def set_regression_mask(self, v):
        """"""
        base = self._base
        index = np.arange(v.size())
        np.random.shuffle(index)
        ones = np.ones(v.size())
        ones[index[int(base._tr_fraction * v.size()):]] = 0
        base._mask = SparseArray.fromlist(ones)
105805
def set_maskalpha(self):
        """"""
        try:
            a = float(self.w.mask_alpha.get_text())
        except ValueError:
            self.logger.error('Cannot set mask alpha')
            self.w.mask_alpha.set_text(str(self.maskalpha))
            return

        if a < 0 or a > 1:
            self.logger.error('Alpha must be between 0 and 1, inclusive')
            self.w.mask_alpha.set_text(str(self.maskalpha))
            return

        self.maskalpha = a
1309984
public static BufferedImage applyMask(BufferedImage image, int rgba)
    {
        final BufferedImage mask = copyImage(image);
        final int height = mask.getHeight();
        final int width = mask.getWidth();

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                final int col = mask.getRGB(x, y);
                final int flag = 0x00_FF_FF_FF;
                if (col == rgba)
                {
                    mask.setRGB(x, y, col & flag);
                }
            }
        }
        return mask;
    }
405971
def set_membind(nodemask):
    
    mask = set_to_numa_nodemask(nodemask)

    tmp = bitmask_t()
    tmp.maskp = cast(byref(mask), POINTER(c_ulong))
    tmp.size = sizeof(nodemask_t) * 8

    libnuma.numa_set_membind(byref(tmp))
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, ]
1058359
def combine(method, images, masks=None, dtype=None,
            region=None, zeros=None, scales=None, weights=None,
            include_variance=True, datamodel=None, method_name=""):
    """'"""

    import numina.datamodel

    nimages = len(images)

    # processing masks
    if masks is None:
        intl_masks = [None for _ in images]
    elif isinstance(masks, Extension):
        intl_masks = [img[masks.name].data for img in images]
    elif isinstance(masks, collections.Sequence):
        intl_masks = [mask[0].data for mask in masks]
    else:
        raise TypeError('mask in invalid')

    if len(intl_masks) != nimages:
        raise TypeError('len(masks) != len(images)')

    # Processing region
    if region is None:
        region = Ellipsis # meaning arr[...]

    # processing zeros, scales and weights
    num_values = dict(zeros=None, scales=None, weights=None)
    arg_values = dict(zeros=zeros, scales=scales, weights=weights)

    for key in num_values:
        arg = arg_values[key] # locals()[key]
        value_arg, arg_is_func = _inspect_method(arg)
        if arg_is_func:
            num_values[key] = [value_arg(img, mask, region) for img, mask in zip(images, intl_masks)]
        else:
            num_values[key] = value_arg
        if num_values[key] is not None:
            # Intl combine works only with np arrays
            num_values[key] = numpy.array(num_values[key])

    arrays = [hdu[0].data for hdu in images]
    if masks is None:
        fmasks = None
    else:
        fmasks = intl_masks

    out = C.generic_combine(
        method, arrays, masks=fmasks, dtype=dtype, out=None,
        zeros=num_values['zeros'], scales=num_values['scales'],
        weights=num_values['weights'])

    # Build HDUList
    headers = [img[0].header for img in images]

    base_header = headers[0].copy()
    hdu1 = fits.PrimaryHDU(data=out[0], header=base_header)
    list_of_hdu = [hdu1]

    #_logger.debug('update result header')
    prolog = ""
    if prolog:
        #_logger.debug('write prolog')
        hdu1.header['history'] = prolog

    if method_name != "":
        #_logger.info("Combined %d images using '%s'", nimages, method.__name__)
        hdu1.header['history'] = "Combined %d images using '%s'" % (nimages, method)
    else:
        hdu1.header['history'] = "Combined %d images" % (nimages,)

    hdu1.header['history'] = 'Combination time {}'.format(datetime.datetime.utcnow().isoformat())

    if datamodel is None:
        datamodel = numina.datamodel.DataModel()

    for idx, img in enumerate(images, start=1):
        hdu1.header['history'] = "Image{} {}".format(idx, datamodel.get_imgid(img))

    prevnum = base_header.get('NUM-NCOM', 1)

    hdu1.header['NUM-NCOM'] = prevnum * nimages
    hdu1.header['UUID'] = str(uuid.uuid1())

    # Headers of last image
    # hdu1.header['TSUTC2'] = headers[-1]['TSUTC2']

    if include_variance:
        varhdu = fits.ImageHDU(out[1], name='VARIANCE')
        list_of_hdu.append(varhdu)

    num = fits.ImageHDU(out[2].astype('uint8'), name='MAP')
    list_of_hdu.append(num)

    result = fits.HDUList(list_of_hdu)
    return result
136945
def set_moving_image(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, False)
        self.moving_image = image
426155
def mask_by_value(self, nodata):
        
        return self.copy_with(image=np.ma.masked_array(self.image.data, mask=self.image.data == nodata))
130791
function(image, x, y, options) {
        var result = false;
        var data = options.data;
        if (!data)
            return result;
        var mask = this._getImageMask(image, options);
        var imageMaskWidth = this._getMaskX(image.width);
        var maskShiftX = this._getMaskX(x);
        var maskShiftY = this._getMaskY(y);
        for (var i = 0; i < mask.length; i++) {
            if (!mask[i])
                continue;
            var maskX = maskShiftX + (i % imageMaskWidth);
            var maskY = maskShiftY + Math.floor(i / imageMaskWidth);
            var key = this._getIndexKey(maskX, maskY);
            this._addDataToIndex(key, options);
            result = true;
        }
        return result;
    }
285040
def create_mask(self):
        
        ntags = len(self._drawn_tags)

        if ntags == 0:
            return

        old_image = self.fitsimage.get_image()

        if old_image is None:
            return

        mask = None
        obj_kinds = set()

        # Create mask
        for tag in self._drawn_tags:
            obj = self.canvas.get_object_by_tag(tag)

            try:
                cur_mask = old_image.get_shape_mask(obj)
            except Exception as e:
                self.logger.error('Cannot create mask: {0}'.format(str(e)))
                continue

            if mask is not None:
                mask |= cur_mask
            else:
                mask = cur_mask

            obj_kinds.add(obj.kind)

        # Might be useful to inherit header from displayed image (e.g., WCS)
        # but the displayed image should not be modified.
        # Bool needs to be converted to int so FITS writer would not crash.
        image = dp.make_image(mask.astype('int16'), old_image, {},
                              pfx=self._mask_prefix)
        imname = image.get('name')

        # Insert new image
        self.fv.gui_call(self.fv.add_image, imname, image, chname=self.chname)

        # Add description to ChangeHistory
        s = 'Mask created from {0} drawings ({1})'.format(
            ntags, ','.join(sorted(obj_kinds)))
        info = dict(time_modified=datetime.utcnow(), reason_modified=s)
        self.fv.update_image_info(image, info)
        self.logger.info(s)
335583
def spur(image, mask=None, iterations=1):
    '''
    '''
    global spur_table_1,spur_table_2
    if mask is None:
        masked_image = image
    else:
        masked_image = image.astype(bool).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):
        for table in (spur_table_1, spur_table_2):
            index_i, index_j = index_lookup(index_i, index_j, 
                                            masked_image, table, 1)
    masked_image = extract_from_image_lookup(image, index_i, index_j)
    if not mask is None:
        masked_image[~mask] = image[~mask]
    return masked_image
1030838
def update_metric(self, metric, labels, pre_sliced=False):
        """"""
        for current_exec, (texec, islice) in enumerate(zip(self.train_execs, self.slices)):
            if not pre_sliced:
                labels_slice = [label[islice] for label in labels]
            else:
                labels_slice = labels[current_exec]
            metric.update(labels_slice, texec.outputs)
1196487
def _set_image(self, image, nodata=None):
        
        # convert to masked array:
        if isinstance(image, np.ma.core.MaskedArray):
            masked = image
        elif isinstance(image, np.core.ndarray):
            masked = self._build_masked_array(image, nodata)
        else:
            raise GeoRaster2NotImplementedError('only ndarray or masked array supported, got %s' % type(image))

        # make sure array is 3d:
        if len(masked.shape) == 3:
            self._image = masked
        elif len(masked.shape) == 2:
            self._image = masked[np.newaxis, :, :]
        else:
            raise GeoRaster2Error('expected 2d or 3d image, got shape=%s' % masked.shape)

        # update shape
        if self._shape is None:
            self._set_shape(self._image.shape)

        self._image_after_load_validations()
        if self._image_readonly:
            self._image.setflags(write=0)
21201
public void setCropArea(int x, int y, int width, int height) {

        m_cropX = x;
        m_cropY = y;
        m_cropWidth = width;
        m_cropHeight = height;
    }
387196
def iMath_propagate_labels_through_mask(image, labels, stopping_value=100, propagation_method=0):
    
    return iMath(image, 'PropagateLabelsThroughMask', labels, stopping_value, propagation_method)
1026784
def image_set_aspect(aspect=1.0, axes="gca"):
    
    if axes is "gca": axes = _pylab.gca()

    e = axes.get_images()[0].get_extent()
    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)