async def __call__(self, image: Image) -> Image: """Remove background from image. Args: image: Image to remove background from. Returns: Image without background. """ from photutils.background import Background2D, MedianBackground # init objects sigma_clip = SigmaClip(sigma=self.sigma) bkg_estimator = MedianBackground() # calculate background bkg = Background2D(image.data, self.box_size, filter_size=self.filter_size, sigma_clip=sigma_clip, bkg_estimator=bkg_estimator) # copy image and remove background img = image.copy() img.data = img.data - bkg.background return img
def photutilsky(image, box_size=(50, 50), filter_size=(3, 3)): """ Estimate sky background using photutils.""" sigma_clip = SigmaClip(sigma=3.) bkg_estimator = MedianBackground() bkg = Background2D(image.data, box_size, mask=image.mask, filter_size=filter_size, sigma_clip=sigma_clip) return bkg.background
def find_sources_via_segmentation(data, sigma=3, fwhm=2.0, min_pix=5, make_plot=False): """ """ yd, xd = data.shape # Let's define the background using boxes of ~50x50 pixels nboxx = int(xd / 150) nboxy = int(yd / 150) bkg_estimator = MedianBackground() bkg = Background2D(data, (nboxy, nboxx), filter_size=(3, 3), bkg_estimator=bkg_estimator) data -= bkg.background # subtract the background threshold = sigma * bkg.background_rms #threshold = detect_threshold(data, nsigma=sigma) gaussian_sigma = fwhm * gaussian_fwhm_to_sigma kernel = Gaussian2DKernel(gaussian_sigma, x_size=3, y_size=3) kernel.normalize(mode='integral') segm = detect_sources(data, threshold, npixels=min_pix, filter_kernel=kernel) segm_deblend = deblend_sources(data, segm, npixels=min_pix, filter_kernel=kernel, nlevels=32, contrast=0.001) if make_plot: norm = ImageNormalize(stretch=SqrtStretch()) fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12.5)) ax1.imshow(data, origin='lower', cmap='Greys_r', norm=norm) ax1.set_title('Data') cmap = segm.make_cmap(seed=123) ax2.imshow(segm, origin='lower', cmap=cmap, interpolation='nearest') ax2.set_title('Segmentation Image') ax3.imshow(segm_deblend, origin='lower', cmap=cmap, interpolation='nearest') ax3.set_title('Deblended Segmentation Image') plt.show() #plt.save('testing.jpg') return data, segm_deblend, bkg
def phot_sources(self, sources=None, peak=True, psf=True): if sources is None: sources = self.sources xx, yy = self.wcs.world_to_pixel_values(sources["ra"], sources["dec"]) x_idx = np.floor(xx + 0.5).astype(int) y_idx = np.floor(yy + 0.5).astype(int) if peak: # Crude Peak Photometry # From pixel indexes to array indexing sources["flux_peak"] = Column(self.data[y_idx, x_idx], unit=self.unit * u.beam).to(u.mJy) sources["eflux_peak"] = Column(self.uncertainty.array[y_idx, x_idx], unit=self.unit * u.beam).to(u.mJy) if psf: # BasicPSFPhotometry with fixed positions sigma_psf = self.beam.sigma_pix.value # Using an IntegratedGaussianPRF can cause biais in the photometry # TODO: Check the NIKA2 calibration scheme # from photutils.psf import IntegratedGaussianPRF # psf_model = IntegratedGaussianPRF(sigma=sigma_psf) psf_model = CircularGaussianPSF(sigma=sigma_psf) psf_model.x_0.fixed = True psf_model.y_0.fixed = True daogroup = DAOGroup(3 * self.beam.fwhm_pix.value) mmm_bkg = MedianBackground() photometry = BasicPSFPhotometry(group_maker=daogroup, bkg_estimator=mmm_bkg, psf_model=psf_model, fitter=LevMarLSQFitter(), fitshape=9) positions = Table([Column(xx, name="x_0"), Column(yy, name="y_0"), Column(self.data[y_idx, x_idx], name="flux_0")]) # Fill the mask with nan to perform correct photometry on the edge # of the mask, and catch numpy & astropy warnings with warnings.catch_warnings(): warnings.simplefilter("ignore", AstropyWarning) warnings.simplefilter("ignore", RuntimeWarning) result_tab = photometry(image=np.ma.array(self.data, mask=self.mask).filled(np.nan), init_guesses=positions) result_tab.sort("id") for _source, _tab in zip(["flux_psf", "eflux_psf"], ["flux_fit", "flux_unc"]): sources[_source] = Column(result_tab[_tab] * psf_model(0, 0), unit=self.unit * u.beam).to(u.mJy) sources["group_id"] = result_tab["group_id"] self.sources = sources
def _background2d(self): """ Estimate the 2D background and background RMS noise in an image. Returns ------- background : `photutils.background.Background2D` A Background2D object containing the 2D background and background RMS noise estimates. """ sigma_clip = SigmaClip(sigma=3.) bkg_estimator = MedianBackground() filter_size = (3, 3) try: bkg = Background2D(self.data, self.box_size, filter_size=filter_size, mask=self.mask, sigma_clip=sigma_clip, bkg_estimator=bkg_estimator) except ValueError: # use the entire unmasked array bkg = Background2D(self.data, self.data.shape, filter_size=filter_size, mask=self.mask, sigma_clip=sigma_clip, bkg_estimator=bkg_estimator, exclude_percentile=100.) log.info('Background could not be estimated in meshes. ' 'Using the entire unmasked array for background ' f'estimation: bkg_boxsize={self.data.shape}.') # apply the coverage mask bkg.background *= np.logical_not(self.mask) bkg.background_rms *= np.logical_not(self.mask) return bkg
def __init__(self, subtract=True, name=None, box_size=(50, 50)): super().__init__(name=None) self.sigma_clip = SigmaClip(sigma=3.) self.bkg_estimator = MedianBackground() self.subtract = subtract self.box_size = box_size
#print(imdata4) #print(imdata[10,998:1003]) #print(imdata[997:1003,1200]) #print(imdata[10,1995:]) #print(imdata[1995:,10]) #print(np.nanmean(np.array(imdata1))) #print(np.nanmean(np.array(imdata2))) #print(np.nanmean(np.array(imdata3))) #print(np.mean(np.array(imdata4))) #print(np.nanmean(np.array(imdata4))) #print(np.median(np.array(imdata4))) sigma_clip = SigmaClip(sigma=3.) bkg_estimator = MedianBackground() bkg1 = Background2D(imdata1, imdata1.shape, filter_size=(3, 3), sigma_clip=sigma_clip, bkg_estimator=bkg_estimator) print('bkg1.background_median = ', bkg1.background_median) print('bkg1.background_rms_median = ', bkg1.background_rms_median) bkg2 = Background2D(imdata2, imdata2.shape, filter_size=(3, 3), sigma_clip=sigma_clip, bkg_estimator=bkg_estimator) print('bkg2.background_median = ', bkg2.background_median)