list of background correction parameters
438004
def info(self):
        """"""
        info = []
        name = self.__class__.__name__.lower()
        # get bg information
        for key in VALID_BG_KEYS:
            if key in self.h5["bg_data"]:
                attrs = self.h5["bg_data"][key].attrs
                for akey in attrs:
                    atr = attrs[akey]
                    var = "{} background {}".format(name, akey)
                    info.append((var, atr))
        if "fit" in self.h5["bg_data"]:
            # mask background
            var_mask = "{} background from mask".format(name)
            if ("estimate_bg_from_mask" in self.h5
                    and self.h5["estimate_bg_from_mask"] is not None):
                # bg was computed from mask image
                info.append((var_mask, True))
            elif ("estimate_bg_from_binary" in self.h5
                    and self.h5["estimate_bg_from_binary"] is not None):
                # bg was computed from mask image (old notation)
                warnings.warn("Old file format detected!", DeprecationWarning)
                info.append((var_mask, True))
            else:
                info.append((var_mask, False))
        return info
1239827
def _add_detection_gt(self, img, add_mask):
        
        # ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])
        # objs = self.coco.loadAnns(ann_ids)
        objs = self.coco.imgToAnns[img['image_id']]  # equivalent but faster than the above two lines

        # clean-up boxes
        valid_objs = []
        width = img.pop('width')
        height = img.pop('height')
        for objid, obj in enumerate(objs):
            if obj.get('ignore', 0) == 1:
                continue
            x1, y1, w, h = obj['bbox']
            # bbox is originally in float
            # x1/y1 means upper-left corner and w/h means true w/h. This can be verified by segmentation pixels.
            # But we do make an assumption here that (0.0, 0.0) is upper-left corner of the first pixel

            x1 = np.clip(float(x1), 0, width)
            y1 = np.clip(float(y1), 0, height)
            w = np.clip(float(x1 + w), 0, width) - x1
            h = np.clip(float(y1 + h), 0, height) - y1
            # Require non-zero seg area and more than 1x1 box size
            if obj['area'] > 1 and w > 0 and h > 0 and w * h >= 4:
                obj['bbox'] = [x1, y1, x1 + w, y1 + h]
                valid_objs.append(obj)

                if add_mask:
                    segs = obj['segmentation']
                    if not isinstance(segs, list):
                        assert obj['iscrowd'] == 1
                        obj['segmentation'] = None
                    else:
                        valid_segs = [np.asarray(p).reshape(-1, 2).astype('float32') for p in segs if len(p) >= 6]
                        if len(valid_segs) == 0:
                            logger.error("Object {} in image {} has no valid polygons!".format(objid, img['file_name']))
                        elif len(valid_segs) < len(segs):
                            logger.warn("Object {} in image {} has invalid polygons!".format(objid, img['file_name']))

                        obj['segmentation'] = valid_segs

        # all geometrically-valid boxes are returned
        boxes = np.asarray([obj['bbox'] for obj in valid_objs], dtype='float32')  # (n, 4)
        cls = np.asarray([
            self.COCO_id_to_category_id[obj['category_id']]
            for obj in valid_objs], dtype='int32')  # (n,)
        is_crowd = np.asarray([obj['iscrowd'] for obj in valid_objs], dtype='int8')

        # add the keys
        img['boxes'] = boxes        # nx4
        img['class'] = cls          # n, always >0
        img['is_crowd'] = is_crowd  # n,
        if add_mask:
            # also required to be float32
            img['segmentation'] = [
                obj['segmentation'] for obj in valid_objs]
443967
def _background_color(s):
        
        seed(s)
        r = v = b = 255
        while r + v + b > 255 * 2:
            r = randint(0, 255)
            v = randint(0, 255)
            b = randint(0, 255)
        return (r, v, b)
1213905
def _initialize_background(self):
        """"""

        # background vel.
        if len(np.shape(self.U)) == 0:
          self.U = (self.U * np.ones((self.ny)))
        print(np.shape(self.U))
        self.set_U(self.U)

        # the meridional PV gradients in each layer
        self.Qy = (self.beta + np.gradient(np.gradient(self.U, self.dy), self.dy))[np.newaxis,...]


        # complex versions, multiplied by k, speeds up computations to pre-compute
        self.ikQy = np.expand_dims(self.Qy, axis=2) *  1j * self.k

        self.ilQx = 0.
415175
function getBackgroundPositionInPercent(image) {
	var x = 100 * (image.coordinates.x) / (image.properties.width - image.coordinates.width);
	var y = 100 * (image.coordinates.y) / (image.properties.height - image.coordinates.height);
	var template = _.template('<%= (x ? x + "%" : x) %> <%= (y ? y + "%" : y) %>');
	return template({x: x, y: y});
}
430886
private void computePixelFeatures() {
		for (int y = 0; y < derivX.height; y++) {
			int pixelIndex = y*derivX.width;
			int endIndex = pixelIndex+derivX.width;
			for (; pixelIndex < endIndex; pixelIndex++ ) {
				float dx = derivX.data[pixelIndex];
				float dy = derivY.data[pixelIndex];

				// angle from 0 to pi radians
				orientation.data[pixelIndex] = UtilAngle.atanSafe(dy,dx) + GrlConstants.F_PId2;
				// gradient magnitude
				magnitude.data[pixelIndex] = Math.sqrt(dx*dx + dy*dy);
			}
		}
	}
1283295
def match(self,refimage, quiet_identity, **kwargs):
        
        ref_outxy = refimage.outxy
        refWCS = refimage.wcs
        refname = refimage.name
        ref_inxy = refimage.xy_catalog

        cat_src_type = kwargs['cat_src_type']
        del kwargs['cat_src_type']

        if not quiet_identity:
            print("Matching sources from \'{}\' with sources from "
                  "reference {} \'{}\'"
                  .format(self.name, cat_src_type, refname))
        #self.sortSkyCatalog() # apply any catalog sorting specified by the user
        self.transformToRef(refWCS)
        self.refWCS = refWCS
        # extract xyxymatch parameters from input parameters
        matchpars = kwargs.copy()
        self.match_pars = matchpars
        minobj = matchpars['minobj'] # needed for later
        del matchpars['minobj'] # not needed in xyxymatch

        self.goodmatch = True

        # Check to see whether or not it is being matched to itself
        if refname.strip() == self.name.strip():
            self.identityfit = True
            if not quiet_identity:
                log.info('NO fit performed for reference image: %s\n'%self.name)
        else:
            # convert tolerance from units of arcseconds to pixels, as needed
            radius = matchpars['searchrad']
            if matchpars['searchunits'] == 'arcseconds':
                radius /= refWCS.pscale

            # Determine xyoff (X,Y offset) and tolerance to be used with xyxymatch
            if matchpars['use2dhist']:
                xsh, ysh, maxval, flux, zpmat, qual = _estimate_2dhist_shift(
                    self.outxy,
                    ref_outxy,
                    searchrad=radius
                )
                xyoff = (xsh, ysh)

                if matchpars['see2dplot']:
                    zpstd = max(10, flux // 5) if qual else 10
                    title_str = ("Histogram of offsets: Peak has {:d} matches "
                                 "at ({:0.4g}, {:0.4g})"
                                 .format(maxval, xsh, ysh))
                    hist_name = None
                    if not self.interactive:
                        hist_name = 'hist2d_{0}.png'.format(self.rootname)

                    plot_pars = {
                        'data': zpmat,
                        'figure_id': self.figure_id,
                        'vmax': zpstd,
                        'xp': xsh,
                        'yp': ysh,
                        'searchrad': radius,
                        'title_str': title_str,
                        'plotname': hist_name,
                        'interactive': self.interactive
                    }

                    tweakutils.plot_zeropoint(plot_pars)

                if matchpars['see2dplot'] and ('residplot' in matchpars and
                                               'No' in matchpars['residplot']):
                    if self.interactive:
                        prompt = ("Press ENTER for next image, \n" +
                                  "     'n' to continue without updating header or \n" +
                                  "     'q' to quit immediately...\n")

                        if sys.version_info[0] >= 3:
                            a = input(prompt)
                        else:
                            a = raw_input(prompt)

                    else:
                        a = ' '

                    if 'n' in a.lower():
                        self.perform_update = False

                    if 'q' in a.lower():
                        self.quit_immediately = True

                if matchpars['see2dplot']:
                    self.figure_id += 1

            else:
                xoff = 0.
                yoff = 0.
                if not util.is_blank(matchpars['xoffset']):
                    xoff = matchpars['xoffset']
                if not util.is_blank(matchpars['yoffset']):
                    yoff = matchpars['yoffset']
                xyoff = (xoff, yoff)

            matches = xyxymatch(self.outxy, ref_outxy, origin=xyoff,
                                tolerance=matchpars['tolerance'],
                                separation=matchpars['separation'])

            if len(matches) > minobj:
                self.matches['image'] = np.column_stack([matches['input_x'][:,
                                np.newaxis],matches['input_y'][:,np.newaxis]])
                self.matches['ref'] = np.column_stack([matches['ref_x'][:,
                                np.newaxis],matches['ref_y'][:,np.newaxis]])
                self.matches['ref_idx'] = matches['ref_idx']
                self.matches['img_idx'] = self.all_radec[3][matches['input_idx']]
                self.matches['input_idx'] = matches['input_idx']
                self.matches['img_RA'] = self.all_radec[0][matches['input_idx']]
                self.matches['img_DEC'] = self.all_radec[1][matches['input_idx']]

                self.matches['ref_orig_xy'] = np.column_stack([
                                    np.array(ref_inxy[0])[matches['ref_idx']][:,np.newaxis],
                                    np.array(ref_inxy[1])[matches['ref_idx']][:,np.newaxis]])

                self.matches['img_orig_xy'] = np.column_stack([
                    np.array(self.xy_catalog[0])[matches['input_idx']][:,np.newaxis],
                    np.array(self.xy_catalog[1])[matches['input_idx']][:,np.newaxis]])
                self.matches['src_origin'] = ref_inxy[-1][matches['ref_idx']]
                print('Found %d matches for %s...'%(len(matches),self.name))

                if self.pars['writecat']:
                    matchfile = open(self.catalog_names['match'],mode='w+')
                    matchfile.write('#Reference: %s\n'%refname)
                    matchfile.write('#Input: %s\n'%self.name)
                    title = '#Ref_X        Ref_Y        '
                    title += 'Input_X    Input_Y        '
                    title += 'Ref_X0    Ref_Y0        '
                    title += 'Input_X0    Input_Y0        '
                    title += 'Ref_ID    Input_ID        '
                    title += 'Ref_Source\n'
                    fmtstr = '%0.6f    %0.6f        '*4
                    fmtstr += '%d    %d    %s\n'
                    matchfile.write(title)
                    for i in range(len(matches['input_x'])):
                        linestr = fmtstr%\
                            (matches['ref_x'][i],matches['ref_y'][i],\
                             matches['input_x'][i],matches['input_y'][i],
                            self.matches['ref_orig_xy'][:,0][i],
                            self.matches['ref_orig_xy'][:,1][i],
                            self.matches['img_orig_xy'][:,0][i],
                            self.matches['img_orig_xy'][:,1][i],
                            matches['ref_idx'][i],matches['input_idx'][i],
                            self.matches['src_origin'][i])
                        matchfile.write(linestr)
                    matchfile.close()
            else:
                warnstr = textutil.textbox('WARNING: \n'+
                    'Not enough matches (< %d) found for input image: %s'%(minobj,self.name))
                for line in warnstr.split('\n'):
                    log.warning(line)
                print(warnstr)
                self.goodmatch = False
966785
def getDarkCurrentAverages(exposuretimes, imgs):
    '''
    
    '''
    x, imgs_p = sortForSameExpTime(exposuretimes, imgs)
    s0, s1 = imgs[0].shape

    imgs = np.empty(shape=(len(x), s0, s1),
                    dtype=imgs[0].dtype)
    for i, ip in zip(imgs, imgs_p):
        if len(ip) == 1:
            i[:] = ip[0]
        else:
            i[:] = averageSameExpTimes(ip)
    return x, imgs
652725
def asrgb(self, uint8=False, alpha=None, colormap=None,
              dmin=None, dmax=None, **kwargs):
        
        data = self.asarray(**kwargs)
        self = self.keyframe  # self or keyframe
        photometric = self.photometric
        PHOTOMETRIC = TIFF.PHOTOMETRIC

        if photometric == PHOTOMETRIC.PALETTE:
            colormap = self.colormap
            if (colormap.shape[1] < 2**self.bitspersample or
                    self.dtype.char not in 'BH'):
                raise ValueError('cannot apply colormap')
            if uint8:
                if colormap.max() > 255:
                    colormap >>= 8
                colormap = colormap.astype('uint8')
            if 'S' in self.axes:
                data = data[..., 0] if self.planarconfig == 1 else data[0]
            data = apply_colormap(data, colormap)

        elif photometric == PHOTOMETRIC.RGB:
            if 'ExtraSamples' in self.tags:
                if alpha is None:
                    alpha = TIFF.EXTRASAMPLE
                extrasamples = self.extrasamples
                if self.tags['ExtraSamples'].count == 1:
                    extrasamples = (extrasamples,)
                for i, exs in enumerate(extrasamples):
                    if exs in alpha:
                        if self.planarconfig == 1:
                            data = data[..., [0, 1, 2, 3+i]]
                        else:
                            data = data[:, [0, 1, 2, 3+i]]
                        break
            else:
                if self.planarconfig == 1:
                    data = data[..., :3]
                else:
                    data = data[:, :3]
            # TODO: convert to uint8?

        elif photometric == PHOTOMETRIC.MINISBLACK:
            raise NotImplementedError()
        elif photometric == PHOTOMETRIC.MINISWHITE:
            raise NotImplementedError()
        elif photometric == PHOTOMETRIC.SEPARATED:
            raise NotImplementedError()
        else:
            raise NotImplementedError()
        return data
423970
def getGroundResolution(self, latitude, level):
        '''
        
        '''
        latitude = self.clipValue(latitude, self.min_lat, self.max_lat);
        mapSize = self.getMapDimensionsByZoomLevel(level)
        return math.cos(
            latitude * math.pi / 180) * 2 * math.pi * self.earth_radius / \
               mapSize
1265635
function _resizeBackgroundImage($imw, $imh, $cw, $ch, $resize, $repx, $repy, $pba = [], $size = [])
	{
		// pba is background positioning area (from CSS background-origin) may not always be set [x,y,w,h]
		// size is from CSS3 background-size - takes precendence over old resize
		// $w - absolute length or % or auto or cover | contain
		// $h - absolute length or % or auto or cover | contain
		if (isset($pba['w'])) {
			$cw = $pba['w'];
		}
		if (isset($pba['h'])) {
			$ch = $pba['h'];
		}

		$cw = $cw * Mpdf::SCALE;
		$ch = $ch * Mpdf::SCALE;
		if (empty($size) && !$resize) {
			return [$imw, $imh, $repx, $repy];
		}

		if (isset($size['w']) && $size['w']) {
			if ($size['w'] == 'contain') {
				// Scale the image, while preserving its intrinsic aspect ratio (if any),
				// to the largest size such that both its width and its height can fit inside the background positioning area.
				// Same as resize==3
				$h = $imh * $cw / $imw;
				$w = $cw;
				if ($h > $ch) {
					$w = $w * $ch / $h;
					$h = $ch;
				}
			} elseif ($size['w'] == 'cover') {
				// Scale the image, while preserving its intrinsic aspect ratio (if any),
				// to the smallest size such that both its width and its height can completely cover the background positioning area.
				$h = $imh * $cw / $imw;
				$w = $cw;
				if ($h < $ch) {
					$w = $w * $h / $ch;
					$h = $ch;
				}
			} else {
				if (stristr($size['w'], '%')) {
					$size['w'] = (float) $size['w'];
					$size['w'] /= 100;
					$size['w'] = ($cw * $size['w']);
				}
				if (stristr($size['h'], '%')) {
					$size['h'] = (float) $size['h'];
					$size['h'] /= 100;
					$size['h'] = ($ch * $size['h']);
				}
				if ($size['w'] == 'auto' && $size['h'] == 'auto') {
					$w = $imw;
					$h = $imh;
				} elseif ($size['w'] == 'auto' && $size['h'] != 'auto') {
					$w = $imw * $size['h'] / $imh;
					$h = $size['h'];
				} elseif ($size['w'] != 'auto' && $size['h'] == 'auto') {
					$h = $imh * $size['w'] / $imw;
					$w = $size['w'];
				} else {
					$w = $size['w'];
					$h = $size['h'];
				}
			}
			return [$w, $h, $repx, $repy];
		} elseif ($resize == 1 && $imw > $cw) {
			$h = $imh * $cw / $imw;
			return [$cw, $h, $repx, $repy];
		} elseif ($resize == 2 && $imh > $ch) {
			$w = $imw * $ch / $imh;
			return [$w, $ch, $repx, $repy];
		} elseif ($resize == 3) {
			$w = $imw;
			$h = $imh;
			if ($w > $cw) {
				$h = $h * $cw / $w;
				$w = $cw;
			}
			if ($h > $ch) {
				$w = $w * $ch / $h;
				$h = $ch;
			}
			return [$w, $h, $repx, $repy];
		} elseif ($resize == 4) {
			$h = $imh * $cw / $imw;
			return [$cw, $h, $repx, $repy];
		} elseif ($resize == 5) {
			$w = $imw * $ch / $imh;
			return [$w, $ch, $repx, $repy];
		} elseif ($resize == 6) {
			return [$cw, $ch, $repx, $repy];
		}
		return [$imw, $imh, $repx, $repy];
	}
1178848
private static int[][] calculateBlackPoints(byte[] luminances,
                                              int subWidth,
                                              int subHeight,
                                              int width,
                                              int height) {
    int maxYOffset = height - BLOCK_SIZE;
    int maxXOffset = width - BLOCK_SIZE;
    int[][] blackPoints = new int[subHeight][subWidth];
    for (int y = 0; y < subHeight; y++) {
      int yoffset = y << BLOCK_SIZE_POWER;
      if (yoffset > maxYOffset) {
        yoffset = maxYOffset;
      }
      for (int x = 0; x < subWidth; x++) {
        int xoffset = x << BLOCK_SIZE_POWER;
        if (xoffset > maxXOffset) {
          xoffset = maxXOffset;
        }
        int sum = 0;
        int min = 0xFF;
        int max = 0;
        for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width) {
          for (int xx = 0; xx < BLOCK_SIZE; xx++) {
            int pixel = luminances[offset + xx] & 0xFF;
            sum += pixel;
            // still looking for good contrast
            if (pixel < min) {
              min = pixel;
            }
            if (pixel > max) {
              max = pixel;
            }
          }
          // short-circuit min/max tests once dynamic range is met
          if (max - min > MIN_DYNAMIC_RANGE) {
            // finish the rest of the rows quickly
            for (yy++, offset += width; yy < BLOCK_SIZE; yy++, offset += width) {
              for (int xx = 0; xx < BLOCK_SIZE; xx++) {
                sum += luminances[offset + xx] & 0xFF;
              }
            }
          }
        }

        // The default estimate is the average of the values in the block.
        int average = sum >> (BLOCK_SIZE_POWER * 2);
        if (max - min <= MIN_DYNAMIC_RANGE) {
          // If variation within the block is low, assume this is a block with only light or only
          // dark pixels. In that case we do not want to use the average, as it would divide this
          // low contrast area into black and white pixels, essentially creating data out of noise.
          //
          // The default assumption is that the block is light/background. Since no estimate for
          // the level of dark pixels exists locally, use half the min for the block.
          average = min / 2;

          if (y > 0 && x > 0) {
            // Correct the "white background" assumption for blocks that have neighbors by comparing
            // the pixels in this block to the previously calculated black points. This is based on
            // the fact that dark barcode symbology is always surrounded by some amount of light
            // background for which reasonable black point estimates were made. The bp estimated at
            // the boundaries is used for the interior.

            // The (min < bp) is arbitrary but works better than other heuristics that were tried.
            int averageNeighborBlackPoint =
                (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) / 4;
            if (min < averageNeighborBlackPoint) {
              average = averageNeighborBlackPoint;
            }
          }
        }
        blackPoints[y][x] = average;
      }
    }
    return blackPoints;
  }
212606
def check_background(qpi):
    
    for imdat in [qpi._amp, qpi._pha]:
        try:
            fit, attrs = imdat.get_bg(key="fit", ret_attrs=True)
        except KeyError:
            # No bg correction performed
            pass
        else:
            kwargs = dict(attrs)
            # check if we have a user-defined mask image
            binkey = "estimate_bg_from_mask"
            if binkey in imdat.h5:
                kwargs["from_mask"] = imdat.h5[binkey][:]
            else:
                kwargs["from_mask"] = None
            # compute background correction
            with h5py.File("check.h5",
                           driver="core",
                           backing_store=False) as h5:
                # imdat.__class__ is "Amplitude" or "Phase"
                testimdat = imdat.__class__(h5)
                testimdat["raw"] = imdat.raw
                # Set experimental bg data if given
                try:
                    bg = imdat.get_bg("data")
                except KeyError:
                    pass
                else:
                    testimdat.set_bg(bg, key="data")
                # fit bg
                testimdat.estimate_bg(**kwargs)
                # compare
                if not np.allclose(testimdat.get_bg(key="fit"), fit):
                    msg = "Wrong estimated (fitted) background!"
                    raise IntegrityCheckError(msg)
634459
def bk_cyan(cls):
        ""
        wAttributes = cls._get_text_attributes()
        wAttributes &= ~win32.BACKGROUND_MASK
        wAttributes |=  win32.BACKGROUND_CYAN
        cls._set_text_attributes(wAttributes)
759428
private void processSwatch(Bitmap image) {
        final Map<Integer, Integer> colorHistogram = processLuminanceData(image);
        extractFgBgData(colorHistogram);

        // Two-decimal digits of precision for the contrast ratio
        mContrastRatio = Math.round(
                ContrastUtils.calculateContrastRatio(mBackgroundLuminance, mForegroundLuminance)
                * 100.0d) / 100.0d;
    }
1076200
function getBackgroundPoint(vm, size, alignment, chart) {
	// Background Position
	var x = vm.x;
	var y = vm.y;

	var caretSize = vm.caretSize;
	var caretPadding = vm.caretPadding;
	var cornerRadius = vm.cornerRadius;
	var xAlign = alignment.xAlign;
	var yAlign = alignment.yAlign;
	var paddingAndSize = caretSize + caretPadding;
	var radiusAndPadding = cornerRadius + caretPadding;

	if (xAlign === 'right') {
		x -= size.width;
	} else if (xAlign === 'center') {
		x -= (size.width / 2);
		if (x + size.width > chart.width) {
			x = chart.width - size.width;
		}
		if (x < 0) {
			x = 0;
		}
	}

	if (yAlign === 'top') {
		y += paddingAndSize;
	} else if (yAlign === 'bottom') {
		y -= size.height + paddingAndSize;
	} else {
		y -= (size.height / 2);
	}

	if (yAlign === 'center') {
		if (xAlign === 'left') {
			x += paddingAndSize;
		} else if (xAlign === 'right') {
			x -= paddingAndSize;
		}
	} else if (xAlign === 'left') {
		x -= radiusAndPadding;
	} else if (xAlign === 'right') {
		x += radiusAndPadding;
	}

	return {
		x: x,
		y: y
	};
}
949387
def clearOldCalibrations(self, date=None):
        '''
        
        '''
        self.coeffs['dark current'] = [self.coeffs['dark current'][-1]]
        self.coeffs['noise'] = [self.coeffs['noise'][-1]]

        for light in self.coeffs['flat field']:
            self.coeffs['flat field'][light] = [
                self.coeffs['flat field'][light][-1]]
        for light in self.coeffs['lens']:
            self.coeffs['lens'][light] = [self.coeffs['lens'][light][-1]]