How to use the photutils.detect_sources function in photutils

To help you get started, we’ve selected a few photutils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vortex-exoplanet / VIP / vip_hci / metrics / roc.py View on Github external
list_binmaps = []
    sizey, sizex = frame.shape
    cy, cx = frame_center(frame)
    reselem_mask = get_circle(frame, radius=fwhm, cy=cy, cx=cx, mode="val")
    npix_circ_aperture = reselem_mask.shape[0]

    # normalize injections: accepts combinations of 1d/2d and tuple/list/array.
    injections = np.asarray(injections)
    if injections.ndim == 1:
        injections = np.array([injections])

    for ithr, threshold in enumerate(thresholds):
        if debug:
            print("\nprocessing threshold #{}: {}".format(ithr + 1, threshold))

        segments = detect_sources(frame, threshold, npix, connectivity=4)
        binmap = (segments.data != 0)

        if debug:
            plots(segments.data, binmap, cmap=('tab10', 'bone'),
                  circle=[tuple(xy) for xy in injections], circlerad=fwhm,
                  circlealpha=0.6, label=["segmentation map", "binary map"])

        detections = 0
        fps = 0

        for iblob in segments.labels:
            blob_mask = (segments.data == iblob)
            blob_area = segments.areas[iblob - 1]

            if debug:
                plots(blob_mask, circle=[tuple(xy) for xy in injections],
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / magic / misc / imageimporter.py View on Github external
# because we want to remove the star and its diffraction spikes. So, we want to remove these little blobs of nan from the nan_mask,
        # and interpolate the image there ... So here we seperate the nan_mask into a new mask without the little blobs, and a mask consisting
        # of only these blobs.

        from ..tools import plotting
        #plotting.plot_box(nan_mask[1200:1300, 700:790], "nan mask")

        #eroded_nan_mask = nan_mask.eroded()
        #plotting.plot_box(eroded_nan_mask[1200:1300, 700:790], "eroded nan mask")

        #blob_mask = nan_mask - eroded_nan_mask
        #plotting.plot_box(blob_mask[1200:1300, 700:790], "blob mask")
        #plotting.plot_box(blob_mask, "blob mask")

        from photutils import detect_sources
        segments = detect_sources(nan_mask.astype(float), 0.1, 1).data

        # Check where the nan_mask hits the boundary
        hits_boundary, where = nan_mask.hits_boundary(where=True)

        blob_mask = nan_mask.copy()
        if hits_boundary:

            indices = set()

            for pixel in where:
                index = segments[pixel.y, pixel.x]
                indices.add(index)

            #print("indices=", indices)

            for index in indices:
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / magic / basics / mask.py View on Github external
"""
        This function ...
        :return:
        """

        if super: structure = morphology.disk(5, dtype=bool)
        else:
            structure = np.array([[False, True, True, True, False],
                                  [True, True, True, True, True],
                                  [True, True, True, True, True],
                                  [True, True, True, True, True],
                                  [False, True, True, True, False]])

        mask = self.opening(structure)

        segments = detect_sources(mask, 0.5, 1).data

        # Get the label of the center segment
        label = segments[int(0.5*segments.shape[0]), int(0.5*segments.shape[1])]

        # Return the new mask with the appendages removed
        #data, name=None, description=None
        return Mask((segments == label), name=self.name, description=self.description)
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / modeling / maps / maker.py View on Github external
# Check whether the errors frame is present
            assert self.config.errors in reference.frames, "An error map could not be found for the reference image"

            # Create a mask for the pixels with a signal-to-noise ratio of 5 or less
            data = reference.frames[self.config.primary] < self.config.cutoff.level*reference.frames[self.config.errors]
            self.mask = Mask(data)

            # If requested, remove holes from the cut-off mask
            if self.config.cutoff.remove_holes:

                # Save the mask as a FITS file
                Frame(self.mask.astype(float)).save(self.config.saving.cutoff_mask_with_holes_path)

                # Perform the segmentation
                segments = detect_sources(self.mask.astype(float), 0.5, 1).data

                # Save segments
                Frame(segments.astype(float)).save(self.config.saving.cutoff_mask_segments_path)

                # Find the label of the largest segment (=the background)
                label_counts = np.bincount(segments.flatten())
                background_label = np.argmax(label_counts)

                # Create a mask for the holes identified as background
                holes = copy.deepcopy(self.mask)
                holes[segments == background_label] = False

                # Save holes mask
                Frame(holes.astype(float)).save(self.config.saving.cutoff_mask_holes_path)

                # Remove holes from the mask
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / magic / sources / trainedfinder.py View on Github external
# Calculate the detection threshold
        threshold = median + (3.0 * stddev)

        #kernel = self.star_finder.kernel # doesn't work when there was no star extraction on the image, self.star_finder does not have attribute image thus cannot give image.fwhm
        if self.star_finder.config.use_frame_fwhm and self.frame.fwhm is not None:

            fwhm = self.frame.fwhm.to("arcsec").value / self.frame.average_pixelscale.to("arcsec/pix").value
            sigma = fwhm * statistics.fwhm_to_sigma
            kernel = Gaussian2DKernel(sigma)

        else: kernel = self.star_finder.kernel

        try:
            # Create a segmentation map from the frame
            self.segments = Frame(detect_sources(data, threshold, npixels=5, filter_kernel=kernel).data)
        except RuntimeError:

            log.debug("Runtime error during detect_sources ...")
            #log.debug("kernel = " + str(kernel))

            #conv_mode = 'constant'
            #conv_val = 0.0
            #image = ndimage.convolve(data, kernel.array, mode=conv_mode, cval=conv_val)

            #log.debug("median = " + str(median))
            #log.debug("stddev = " + str(stddev))

            #print("image=", image)
            #log.debug("image.ndim = " + str(image.ndim))
            #log.debug("type image = " + type(image))
            #log.debug("image.shape = "+ str(image.shape))
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / magic / basics / mask.py View on Github external
def fill_holes(self):

        """
        This function ...
        :return:
        """

        # Create a copy of this mask
        new_mask = self.copy()

        # Perform the segmentation
        segments = detect_sources(self.inverse().astype(float), 0.5, 1).data

        # Find the label of the largest segment (=the background)
        label_counts = np.bincount(segments.flatten())
        if len(label_counts) > 1:

            background_label = np.argmax(label_counts[1:]) + 1
            # If the source mask is larger than the background (in number of pixels), the above will provide the correct label
            # therefore we do the '[1:]'

            # Create a mask for the holes identified as background
            holes = self.inverse().copy()
            holes[segments == background_label] = False

            # Remove holes from the mask
            new_mask[holes] = True
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / magic / core / source.py View on Github external
:param min_pixels:
        :return:
        """

        # If a subtracted box is present, use it to find the center segment
        box = self.subtracted if self.has_background else self.cutout

        if not np.all(self.mask):

            mean, median, stddev = statistics.sigma_clipped_statistics(box, mask=self.mask)
            threshold = mean + stddev * sigma_level

        else: threshold = detect_threshold(box, snr=2.0) #snr=2.0

        # Perform the segmentation
        segments = detect_sources(box, threshold, npixels=min_pixels, filter_kernel=kernel).data

        # To plot the multiple segments that are detected
        #if segments.max() > 1: plotting.plot_box(np.ma.masked_array(box, mask=segments.astype(bool)))

        # Get the label of the center segment
        rel_center = self.cutout.rel_position(self.center)
        try:
            label = segments[int(round(rel_center.y)), int(round(rel_center.x))]
        except:
            try:
                label = segments[int(rel_center.y), int(rel_center.x)]
            except:
                return Mask((segments == label))

        # If the center pixel is identified as being part of the background, create an empty mask (the center does not
        # correspond to a segment)