Measurement of the separation quality for a given image in terms of
    filtered true source, spatial error, interference and artifacts.
170323
def _bss_image_crit(s_true, e_spat, e_interf, e_artif):
    
    # energy ratios
    sdr = _safe_db(np.sum(s_true**2), np.sum((e_spat+e_interf+e_artif)**2))
    isr = _safe_db(np.sum(s_true**2), np.sum(e_spat**2))
    sir = _safe_db(np.sum((s_true+e_spat)**2), np.sum(e_interf**2))
    sar = _safe_db(np.sum((s_true+e_spat+e_interf)**2), np.sum(e_artif**2))
    return (sdr, isr, sir, sar)
1255864
def quality_comparator(video_data):
        """"""
        def parse_resolution(res: str) -> Tuple[int, ...]:
            return tuple(map(int, res.split('x')))

        raw_resolution = video_data['resolution']
        resolution = parse_resolution(raw_resolution)
        return resolution
113290
function() {

  var b = test_batch;
  var k = Math.floor(Math.random()*num_samples_per_batch);
  var n = b*num_samples_per_batch+k;

  var p = img_data[b].data;
  var x = new convnetjs.Vol(image_dimension,image_dimension,image_channels,0.0);
  var W = image_dimension*image_dimension;
  var j=0;
  for(var dc=0;dc<image_channels;dc++) {
    var i=0;
    for(var xc=0;xc<image_dimension;xc++) {
      for(var yc=0;yc<image_dimension;yc++) {
        var ix = ((W * k) + i) * 4 + dc;
        x.set(yc,xc,dc,p[ix]/255.0-0.5);
        i++;
      }
    }
  }

  // distort position and maybe flip
  var xs = [];
  
  if (random_flip || random_position){
    for(var k=0;k<6;k++) {
      var test_variation = x;
      if(random_position){
        var dx = Math.floor(Math.random()*5-2);
        var dy = Math.floor(Math.random()*5-2);
        test_variation = convnetjs.augment(test_variation, image_dimension, dx, dy, false);
      }
      
      if(random_flip){
        test_variation = convnetjs.augment(test_variation, image_dimension, 0, 0, Math.random()<0.5); 
      }

      xs.push(test_variation);
    }
  }else{
    xs.push(x, image_dimension, 0, 0, false); // push an un-augmented copy
  }
  
  // return multiple augmentations, and we will average the network over them
  // to increase performance
  return {x:xs, label:labels[n]};
}
165763
def _coarsenImage(image, f):
    '''
    
    '''
    from skimage.morphology import square
    from skimage.filters import rank
    from skimage.transform._warps import rescale
    selem = square(f)
    arri = rank.mean(image, selem=selem)
    return rescale(arri, 1 / f, order=0)
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;
    }
1280940
private static void adjustQualityFromImage(Map<String, Float> pFormatQuality, BufferedImage pImage) {
        // NOTE: The values are all made-up. May need tuning.

        // If pImage.getColorModel() instanceof IndexColorModel
        //    JPEG qs*=0.6
        //    If NOT binary or 2 color index
        //        WBMP qs*=0.5
        // Else
        //    GIF qs*=0.02
        //    PNG qs*=0.9 // JPEG is smaller/faster
        if (pImage.getColorModel() instanceof IndexColorModel) {
            adjustQuality(pFormatQuality, FORMAT_JPEG, 0.6f);

            if (pImage.getType() != BufferedImage.TYPE_BYTE_BINARY ||  ((IndexColorModel) pImage.getColorModel()).getMapSize() != 2) {
                adjustQuality(pFormatQuality, FORMAT_WBMP, 0.5f);
            }
        }
        else {
            adjustQuality(pFormatQuality, FORMAT_GIF, 0.01f);
            adjustQuality(pFormatQuality, FORMAT_PNG, 0.99f); // JPEG is smaller/faster
        }

        // If pImage.getColorModel().hasTransparentPixels()
        //    JPEG qs*=0.05
        //    WBMP qs*=0.05
        //    If NOT transparency == BITMASK
        //        GIF qs*=0.8
        if (ImageUtil.hasTransparentPixels(pImage, true)) {
            adjustQuality(pFormatQuality, FORMAT_JPEG, 0.009f);
            adjustQuality(pFormatQuality, FORMAT_WBMP, 0.009f);

            if (pImage.getColorModel().getTransparency() != Transparency.BITMASK) {
                adjustQuality(pFormatQuality, FORMAT_GIF, 0.8f);
            }
        }
    }
892986
def SNR(img1, img2=None, bg=None,
        noise_level_function=None,
        constant_noise_level=False,
        imgs_to_be_averaged=False):
    '''
    
    '''
    # dark current subtraction:
    img1 = np.asfarray(img1)
    if bg is not None:
        img1 = img1 - bg

    # SIGNAL:
    if img2 is not None:
        img2_exists = True
        img2 = np.asfarray(img2) - bg
        # signal as average on both images
        signal = 0.5 * (img1 + img2)
    else:
        img2_exists = False
        signal = img1
    # denoise:
    signal = median_filter(signal, 3)

    # NOISE
    if constant_noise_level:
        # CONSTANT NOISE
        if img2_exists:
            d = img1 - img2
            # 0.5**0.5 because of sum of variances
            noise = 0.5**0.5 * np.mean(np.abs((d))) * F_RMS2AAD
        else:
            d = (img1 - signal) * F_NOISE_WITH_MEDIAN
            noise = np.mean(np.abs(d)) * F_RMS2AAD
    else:
        # NOISE LEVEL FUNCTION
        if noise_level_function is None:
            noise_level_function, _ = oneImageNLF(img1, img2, signal)
        noise = noise_level_function(signal)
        noise[noise < 1] = 1  # otherwise SNR could be higher than image value

    if imgs_to_be_averaged:
        # SNR will be higher if both given images are supposed to be averaged:
        # factor of noise reduction if SNR if for average(img1, img2):
        noise *= 0.5**0.5

    # BACKGROUND estimation and removal if background not given:
    if bg is None:
        bg = getBackgroundLevel(img1)
        signal -= bg
    snr = signal / noise

    # limit to 1, saying at these points signal=noise:
    snr[snr < 1] = 1
    return snr
373708
def _deinterlace(self, raw):
        

        # Values per row (of the target image)
        vpr = self.width * self.planes

        # Values per image
        vpi = vpr * self.height
        # Interleaving writes to the output array randomly
        # (well, not quite), so the entire output array must be in memory.
        # Make a result array, and make it big enough.
        if self.bitdepth > 8:
            a = array('H', [0] * vpi)
        else:
            a = bytearray([0] * vpi)
        source_offset = 0

        for lines in adam7_generate(self.width, self.height):
            # The previous (reconstructed) scanline.
            # `None` at the beginning of a pass
            # to indicate that there is no previous line.
            recon = None
            for x, y, xstep in lines:
                # Pixels per row (reduced pass image)
                ppr = int(math.ceil((self.width - x) / float(xstep)))
                # Row size in bytes for this pass.
                row_size = int(math.ceil(self.psize * ppr))

                filter_type = raw[source_offset]
                source_offset += 1
                scanline = raw[source_offset: source_offset + row_size]
                source_offset += row_size
                recon = self.undo_filter(filter_type, scanline, recon)
                # Convert so that there is one element per pixel value
                flat = self._bytes_to_values(recon, width=ppr)
                if xstep == 1:
                    assert x == 0
                    offset = y * vpr
                    a[offset: offset + vpr] = flat
                else:
                    offset = y * vpr + x * self.planes
                    end_offset = (y + 1) * vpr
                    skip = self.planes * xstep
                    for i in range(self.planes):
                        a[offset + i: end_offset: skip] = \
                            flat[i:: self.planes]

        return a
1027951
def separation(X,y,samples=False):
    
    # pdb.set_trace()
    num_classes = len(np.unique(y))
    total_dist = (X.max()-X.min())**2
    if samples:
        # return intra-class distance for each sample
        separation = np.zeros(y.shape)
        for label in np.unique(y):
            for outsider in np.unique(y[y!=label]):
                separation[y==label] += (X[y==label] - np.mean(X[y==outsider])) ** 2

        #normalize between 0 and 1
        print('separation:',separation)
        print('num_classes:',num_classes)
        print('total_dist:',total_dist)
        separation = separation#/separation.max()

        print('separation after normalization:',separation)

    else:
        # return aggregate score
        separation = 0
        for i,label in enumerate(np.unique(y)):
            for outsider in np.unique(y[y!=label]):
                separation += np.sum((X[y==label] - np.mean(X[y==outsider])) ** 2)/len(y[y==label])
        separation = separation/len(np.unique(y))

    return separation
44600
private void computeDivUVD(GrayF32 u , GrayF32 v , GrayF32 psi ,
							   GrayF32 divU , GrayF32 divV , GrayF32 divD ) {

		final int stride = psi.stride;

		// compute the inside pixel
		for (int y = 1; y < psi.height-1; y++) {

			// index of the current pixel
			int index = y*stride + 1;

			for (int x = 1; x < psi.width-1; x++ , index++) {

				float psi_index = psi.data[index];

				float coef0 = 0.5f*(psi.data[index+1] + psi_index);
				float coef1 = 0.5f*(psi.data[index-1] + psi_index);
				float coef2 = 0.5f*(psi.data[index+stride] + psi_index);
				float coef3 = 0.5f*(psi.data[index-stride] + psi_index);

				float u_index = u.data[index];

				divU.data[index] = coef0*(u.data[index+1] - u_index) + coef1*(u.data[index-1] - u_index) +
								   coef2*(u.data[index+stride] - u_index) + coef3*(u.data[index-stride] - u_index);

				float v_index = v.data[index];

				divV.data[index] = coef0*(v.data[index+1] - v_index) + coef1*(v.data[index-1] - v_index) +
								   coef2*(v.data[index+stride] - v_index) + coef3*(v.data[index-stride] - v_index);

				divD.data[index] = coef0 + coef1 + coef2 + coef3;
			}
		}

		// handle the image borders
		for( int x = 0; x < psi.width; x++ ) {
			computeDivUVD_safe(x,0,u,v,psi,divU,divV,divD);
			computeDivUVD_safe(x,psi.height-1,u,v,psi,divU,divV,divD);
		}
		for( int y = 1; y < psi.height-1; y++ ) {
			computeDivUVD_safe(0,y,u,v,psi,divU,divV,divD);
			computeDivUVD_safe(psi.width-1,y,u,v,psi,divU,divV,divD);
		}
	}
932704
def calc_fwhm(img, region, fexpand=3, axis=0):
    """"""

    # We compute know the FWHM of the slit
    # Given the computed position of the slit
    # Expand 'fexpand' pixels around
    # and cut an slice in the median filtered image

    xpregion = expand_region(region, fexpand, fexpand)
    cslit = img[xpregion]

    # Collapse it
    pslit = cslit.mean(axis=axis)

    # Estimate the background as a flat line
    # starting in pslit[0] and ending in pslit[-1]
    x2 = len(pslit)
    y1, y2 = pslit[0], pslit[-1]
    mslope = (y2-y1) / x2
    # background estimation
    backstim = mslope*numpy.arange(x2) + y1

    # We subtract background
    qslit = pslit-backstim
    # and find the pixel of the maximum
    pidx = numpy.argmax(qslit)
    peak, fwhm = fmod.compute_fwhm_1d_simple(qslit, pidx)
    return fwhm
1050198
private void CheckPalleteImage(IfdTags metadata, int nifd) {
    // Color Map
    if (!metadata.containsTagId(TiffTags.getTagId("ColorMap"))) {
      validation.addErrorLoc("Missing Color Map", "IFD" + nifd);
    } else {
      int n = metadata.get(TiffTags.getTagId("ColorMap")).getCardinality();
      if (n != 3 * (int) Math.pow(2, metadata.get(TiffTags.getTagId("BitsPerSample"))
          .getFirstNumericValue()))
        validation.addError("Incorrect Color Map Cardinality", "IFD" + nifd, metadata.get(320)
            .getCardinality());
    }

    // Bits per Sample
    long bps = metadata.get(TiffTags.getTagId("BitsPerSample")).getFirstNumericValue();
    if (bps != 4 && bps != 8)
      validation.addError("Invalid Bits per Sample", "IFD" + nifd, bps);

    // Compression
    long comp = metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue();
    // if (comp != 1 && comp != 32773)
    if (comp < 1)
      validation.addError("Invalid Compression", "IFD" + nifd, comp);
  }
221056
function _imageBlend($mode, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $percent)
    {
        if ($mode == IMAGE_TOOLBOX_BLEND_COPY)
        {
            if ($percent == 100)
            {
                imagecopy($this->_img['main']['resource'], $this->_img['operator']['resource'], $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
            }
            else
            {
                imagecopymerge($this->_img['main']['resource'], $this->_img['operator']['resource'], $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $percent);
            }
        }
        else
        {
            $functionname = $this->_imagecreatefunction;
            $dummy = $functionname($src_w, $src_h);
            for ($y = 0; $y < $src_h; $y++)
            {
                for ($x = 0; $x < $src_w; $x++)
                {
                    $colorindex = imagecolorat($this->_img['main']['resource'], $dst_x + $x, $dst_y + $y);
                    $colorrgb1 = imagecolorsforindex($this->_img['main']['resource'], $colorindex);
                    $colorindex = imagecolorat($this->_img['operator']['resource'], $src_x + $x, $src_y + $y);
                    $colorrgb2 = imagecolorsforindex($this->_img['operator']['resource'], $colorindex);
                    $colorblend = $this->_calculateBlendvalue($mode, $colorrgb1, $colorrgb2);
                    $newcolor = imagecolorallocate($dummy, $colorblend['red'], $colorblend['green'], $colorblend['blue']);
                    imagesetpixel($dummy, $x, $y, $newcolor);
                }
            }

            $this->_img['target']['resource'] = $functionname($this->_img['main']['width'], $this->_img['main']['height']);
            imagecopy($this->_img['target']['resource'], $this->_img['main']['resource'], 0, 0, 0, 0, $this->_img['main']['width'], $this->_img['main']['height']);
            imagecopymerge($this->_img['target']['resource'], $dummy, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $percent);

            $this->_img['main']['resource'] = $this->_img['target']['resource'];
            unset($this->_img['target']);
        }
    }
108733
def channel_portion(image, channel):
    '''
    '''

    # Separate color channels
    rgb = []
    for i in range(3):
        rgb.append(image[:, :, i].astype(int))
    ch = rgb.pop(channel)

    relative_values = ch - np.sum(rgb, axis=0) / 2
    relative_values = np.maximum(np.zeros(ch.shape), relative_values)

    return float(np.average(relative_values) / 255)
694428
protected double[][] extractFeaturesInternal(BufferedImage image) {

		double[][] descriptions = harder(image);
		if (!perBandNormalization) {
			// if perBandNormalization is off then do a final L2 normalization
			for (int i = 0; i < descriptions.length; i++) {
				Normalization.normalizeL2(descriptions[i]);
				// SurfDescribeOps.normalizeFeatures(descriptions[i]);
			}
		}
		return descriptions;
	}
970838
def do_quality(self, quality):
        
        if (quality == 'grey' or quality == 'gray'):
            # Checking for 1.1 gray or 20.0 grey elsewhere
            self.logger.debug("quality: converting to gray")
            self.image = self.image.convert('L')
        elif (quality == 'bitonal'):
            self.logger.debug("quality: converting to bitonal")
            self.image = self.image.convert('1')
        else:  # color or default/native (which we take as color)
            # Deal first with conversions from I;16* formats which Pillow
            # appears not to handle properly, resulting in mostly white images
            # if we convert directly. See:
            # <http://stackoverflow.com/questions/7247371/python-and-16-bit-tiff>
            if (self.image.mode.startswith('I;16')):
                self.logger.debug("quality: fudged conversion from mode %s to I"
                                  % (self.image.mode))
                self.image = self.image.convert('I')
                self.image = self.image.point(lambda i: i * (1.0 / 256.0))
            if (self.image.mode not in ('1', 'L', 'RGB', 'RGBA')):
                # Need to convert from palette etc. in order to write out
                self.logger.debug("quality: converting from mode %s to RGB"
                                  % (self.image.mode))
                self.image = self.image.convert('RGB')
            else:
                self.logger.debug("quality: quality (nop)")
310653
private void process(int[] srcImage, int[] dstImage, int x, int y)
    {
        final int b = getSourcePixel(srcImage, x, y - 1);
        final int d = getSourcePixel(srcImage, x - 1, y);
        final int e = getSourcePixel(srcImage, x, y);
        final int f = getSourcePixel(srcImage, x + 1, y);
        final int h = getSourcePixel(srcImage, x, y + 1);
        int e0 = e;
        int e1 = e;
        int e2 = e;
        int e3 = e;
        if (b != h && d != f)
        {
            e0 = d == b ? d : e;
            e1 = b == f ? f : e;
            e2 = d == h ? d : e;
            e3 = h == f ? f : e;
        }

        setDestPixel(dstImage, x * SCALE, y * SCALE, e0);
        setDestPixel(dstImage, x * SCALE + 1, y * SCALE, e1);
        setDestPixel(dstImage, x * SCALE, y * SCALE + 1, e2);
        setDestPixel(dstImage, x * SCALE + 1, y * SCALE + 1, e3);
    }