Image quality metric based on maximal signal power vs. power of the noise.

  Args:
    true: the ground truth image.
    pred: the predicted image.
  Returns:
    peak signal to noise ratio (PSNR)
353705
def peak_signal_to_noise_ratio(true, pred):
  
  return 10.0 * tf.log(1.0 / mean_squared_error(true, pred)) / tf.log(10.0)
111765
def V(self, brightest=False):
        
        mags = self.get_photometry(brightest=brightest, convert=False)
        VT, dVT = mags['VT']
        BT, dBT = mags['BT']
        if (-0.25 < BT - VT < 2.0):
            (a, b, c, d) = (0.00097, 0.1334, 0.05486, 0.01998)
            V = (VT + a - b * (BT - VT) + c * (BT - VT)**2 -
                d * (BT - VT)**3)

            dVdVT = 1 + b - 2*c*(BT-VT) + 3*d*(BT-VT)**2
            dVdBT = -b + 2*c*(BT-VT) - 3*d*(BT-VT)**2
            dV = np.sqrt((dVdVT**2 * dVT**2) + (dVdBT**2*dBT**2))

        else:
            raise ValueError('BT-VT outside of range to convert')

        return V, dV
210810
def accuracy_thresh(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
    ""
    if sigmoid: y_pred = y_pred.sigmoid()
    return ((y_pred>thresh)==y_true.byte()).float().mean()
331500
def image_resolution(self) -> Optional[Tuple[int, int]]:
        

        """
        images = self.attributes.get('imageinfo', [])
        if images and isinstance(images, collections.abc.Sequence):
            img = images[0]
            return img['width'], img['height']
        return None
1313994
boolean computeRectifyH( double f1 , double f2 , DMatrixRMaj P2, DMatrixRMaj H ) {

		estimatePlaneInf.setCamera1(f1,f1,0,0,0);
		estimatePlaneInf.setCamera2(f2,f2,0,0,0);

		if( !estimatePlaneInf.estimatePlaneAtInfinity(P2,planeInf) )
			return false;

		// TODO add a cost for distance from nominal and scale other cost by focal length fx for each view
//		RefineDualQuadraticConstraint refine = new RefineDualQuadraticConstraint();
//		refine.setZeroSkew(true);
//		refine.setAspectRatio(true);
//		refine.setZeroPrinciplePoint(true);
//		refine.setKnownIntrinsic1(true);
//		refine.setFixedCamera(false);
//
//		CameraPinhole intrinsic = new CameraPinhole(f1,f1,0,0,0,0,0);
//		if( !refine.refine(normalizedP.toList(),intrinsic,planeInf))
//			return false;

		K1.zero();
		K1.set(0,0,f1);
		K1.set(1,1,f1);
		K1.set(2,2,1);
		MultiViewOps.createProjectiveToMetric(K1,planeInf.x,planeInf.y,planeInf.z,1,H);

		return true;
	}
21776
def _image_of_size(image_size):
  """"""
  return np.random.uniform(0, 256, [image_size, image_size, 3]).astype(np.uint8)
1071783
def get_qpimage_raw(self, idx):
        """"""
        ds = self._get_dataset(idx)
        qpi = ds.get_qpimage_raw()
        qpi["identifier"] = self.get_identifier(idx)
        return qpi
244679
def finite_pixels(self):
        
        finite_px = np.where(np.isfinite(self.data))
        finite_px = np.c_[finite_px[0], finite_px[1]]
        return finite_px
1079484
def _validate_pixel_density(self):
        
        for f in [f for f in self.mets.find_files() if f.mimetype.startswith('image/')]:
            if not f.local_filename and not self.download:
                self.report.add_notice("Won't download remote image <%s>" % f.url)
                continue
            exif = self.workspace.resolve_image_exif(f.url)
            for k in ['xResolution', 'yResolution']:
                v = exif.__dict__.get(k)
                if v is None or v <= 72:
                    self.report.add_error("Image %s: %s (%s pixels per %s) is too low" % (f.ID, k, v, exif.resolutionUnit))
588321
def pixels(self, zoom=None):
        """"""
        meter_x, meter_y = self.meters
        pixel_x = (meter_x + ORIGIN_SHIFT) / resolution(zoom=zoom)
        pixel_y = (meter_y - ORIGIN_SHIFT) / resolution(zoom=zoom)
        return abs(round(pixel_x)), abs(round(pixel_y))
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)
845367
def imagetransformerpp_base_8l_8h_big_cond_dr03_dan():
  """"""
  hparams = imagetransformerpp_sep_channels_8l_8h()
  hparams.hidden_size = 512
  hparams.num_heads = 8
  hparams.filter_size = 2048
  hparams.batch_size = 4
  hparams.max_length = 3075
  hparams.layer_prepostprocess_dropout = 0.3
  hparams.layer_preprocess_sequence = "none"
  hparams.layer_postprocess_sequence = "dan"
  hparams.summarize_grads = True
  hparams.learning_rate = 0.01
  return hparams
729559
def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None):
    
    if mask is None:
        mask = np.zeros(image.shape[:2], dtype=np.uint8)
        mask[:] = 255

    if len(image.shape) > 2 and image.shape[2] == 4:
        image = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
    res = _calc_block_mean_variance(image, mask, block_size)
    res = image.astype(np.float32) - res.astype(np.float32) + 255
    _, res = cv2.threshold(res, 215, 255, cv2.THRESH_BINARY)
    return res
384522
def prewitt(image, mask=None):
    '''
    '''
    return np.sqrt(hprewitt(image,mask)**2 + vprewitt(image,mask)**2)
1130181
def __demodulate_data(self, data):
        
        if len(data) == 0:
            return

        power_spectrum = data.real ** 2 + data.imag ** 2
        is_above_noise = np.sqrt(np.mean(power_spectrum)) > self.signal.noise_threshold

        if self.adaptive_noise and not is_above_noise:
            self.signal.noise_threshold = 0.9 * self.signal.noise_threshold + 0.1 * np.sqrt(np.max(power_spectrum))

        if is_above_noise:
            self.__add_to_buffer(data)
            self.pause_length = 0
            if not self.__buffer_is_full():
                return
        else:
            self.pause_length += len(data)
            if self.pause_length < 10 * self.signal.bit_len:
                self.__add_to_buffer(data)
                if not self.__buffer_is_full():
                    return

        if self.__current_buffer_index == 0:
            return

        # clear cache and start a new message
        self.signal._fulldata = self.__buffer[0:self.__current_buffer_index]
        self.__clear_buffer()
        self.signal._qad = None

        bit_len = self.signal.bit_len
        if self.automatic_center:
            self.signal.qad_center = AutoInterpretation.detect_center(self.signal.qad, max_size=150*self.signal.bit_len)

        ppseq = grab_pulse_lens(self.signal.qad, self.signal.qad_center,
                                self.signal.tolerance, self.signal.modulation_type, self.signal.bit_len)

        bit_data, pauses, bit_sample_pos = self._ppseq_to_bits(ppseq, bit_len, write_bit_sample_pos=False)

        for bits, pause in zip(bit_data, pauses):
            message = Message(bits, pause, bit_len=bit_len, message_type=self.default_message_type,
                              decoder=self.decoder)
            self.messages.append(message)
            self.message_sniffed.emit(len(self.messages) - 1)
314366
def quantile(image, q, nonzero=True):
    
    img_arr = image.numpy()
    if isinstance(q, (list,tuple)):
        q = [qq*100. if qq <= 1. else qq for qq in q]
        if nonzero:
            img_arr = img_arr[img_arr>0]
        vals = [np.percentile(img_arr, qq) for qq in q]
        return tuple(vals)
    elif isinstance(q, (float,int)):
        if q <= 1.:
            q = q*100.
        if nonzero:
            img_arr = img_arr[img_arr>0]
        return np.percentile(img_arr[img_arr>0], q)
    else:
        raise ValueError('q argument must be list/tuple or float/int')
59006
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\
		           null_grad_thresh=20., null_grad_val = 1./5.):
		
		# weight SNR by chisq
		bestnr = self.get_new_snr(index=index, nhigh=nhigh,
		                          column="chisq")
		if len(self.get_ifos()) < 3:
			return bestnr
		# recontour null SNR threshold for higher SNRs
		if self.snr > null_grad_thresh:
			null_snr_threshold += (self.snr - null_grad_thresh) * null_grad_val
		# weight SNR by null SNR
		if self.get_null_snr() > null_snr_threshold:
			bestnr /= 1 + self.get_null_snr() - null_snr_threshold
		return bestnr