Beispiel #1
0
def get_convex_hull_of_blobs_dog(im):
    """
    Uses the Difference of Gaussian blob detection algorithm from scikit-image to identify the laser points and returns
    a ConvexHull of the points found.
    :param im: Image with laser points in
    :return: ConvexHull of points
    """
    threshold = .15
    tries = 5
    # Get blobs using Difference of Gaussian
    blobs_dog = blob_dog(im, max_sigma=30, threshold=threshold)
    # Compute radii in the 3rd column.
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) # ToDo: Discount blobs with large radii

    while (len(blobs_dog) > 4 or 4 > len(blobs_dog) >= 0) and tries > 0:
        if 2 <= len(blobs_dog) < 4:
            threshold -= 0.05
        elif 6 >= len(blobs_dog) > 4:
            threshold += 0.05
        blobs_dog = blob_dog(im, max_sigma=30, threshold=threshold)
        tries -= 1

    assert len(blobs_dog) == 4, len(blobs_dog)

    return ConvexHull([(blob[0], blob[1]) for blob in blobs_dog])
Beispiel #2
0
def test_blob_dog_excl_border():
    # Testing exclude border

    # image where blob is 5 px from borders, radius 5
    img = np.ones((512, 512))
    xs, ys = disk((5, 5), 5)
    img[xs, ys] = 255
    blobs = blob_dog(
        img,
        min_sigma=1.5,
        max_sigma=5,
        sigma_ratio=1.2,
    )
    assert blobs.shape[0] == 1
    b = blobs[0]
    assert b[0] == b[1] == 5, "blob should be 5 px from x and y borders"

    blobs = blob_dog(
        img,
        min_sigma=1.5,
        max_sigma=5,
        sigma_ratio=1.2,
        exclude_border=6,
    )
    msg = "zero blobs should be detected, as only blob is 5 px from border"
    assert blobs.shape[0] == 0, msg
def test_blob_dog():
    r2 = math.sqrt(2)
    img = np.ones((512, 512))

    xs, ys = circle(400, 130, 5)
    img[xs, ys] = 255

    xs, ys = circle(100, 300, 25)
    img[xs, ys] = 255

    xs, ys = circle(200, 350, 45)
    img[xs, ys] = 255

    blobs = blob_dog(img, min_sigma=5, max_sigma=50)
    radius = lambda x: r2 * x[2]
    s = sorted(blobs, key=radius)
    thresh = 5

    b = s[0]
    assert abs(b[0] - 400) <= thresh
    assert abs(b[1] - 130) <= thresh
    assert abs(radius(b) - 5) <= thresh

    b = s[1]
    assert abs(b[0] - 100) <= thresh
    assert abs(b[1] - 300) <= thresh
    assert abs(radius(b) - 25) <= thresh

    b = s[2]
    assert abs(b[0] - 200) <= thresh
    assert abs(b[1] - 350) <= thresh
    assert abs(radius(b) - 45) <= thresh

    # Testing no peaks
    img_empty = np.zeros((100, 100))
    assert blob_dog(img_empty).size == 0

    # Testing 3D
    r = 10
    pad = 10
    im3 = ellipsoid(r, r, r)
    im3 = util.pad(im3, pad, mode='constant')

    blobs = blob_dog(im3,
                     min_sigma=3,
                     max_sigma=10,
                     sigma_ratio=1.2,
                     threshold=0.1)
    b = blobs[0]

    assert b[0] == r + pad + 1
    assert b[1] == r + pad + 1
    assert b[2] == r + pad + 1
    assert abs(math.sqrt(3) * b[3] - r) < 1
Beispiel #4
0
def test_blob_dog(dtype, threshold_type):
    r2 = math.sqrt(2)
    img = np.ones((512, 512), dtype=dtype)

    xs, ys = disk((400, 130), 5)
    img[xs, ys] = 255

    xs, ys = disk((100, 300), 25)
    img[xs, ys] = 255

    xs, ys = disk((200, 350), 45)
    img[xs, ys] = 255

    if threshold_type == 'absolute':
        threshold = 2.0
        if img.dtype.kind != 'f':
            # account for internal scaling to [0, 1] by img_as_float
            threshold /= img.ptp()
        threshold_rel = None
    elif threshold_type == 'relative':
        threshold = None
        threshold_rel = 0.5

    blobs = blob_dog(
        img,
        min_sigma=4,
        max_sigma=50,
        threshold=threshold,
        threshold_rel=threshold_rel,
    )
    radius = lambda x: r2 * x[2]
    s = sorted(blobs, key=radius)
    thresh = 5
    ratio_thresh = 0.25

    b = s[0]
    assert abs(b[0] - 400) <= thresh
    assert abs(b[1] - 130) <= thresh
    assert abs(radius(b) - 5) <= ratio_thresh * 5

    b = s[1]
    assert abs(b[0] - 100) <= thresh
    assert abs(b[1] - 300) <= thresh
    assert abs(radius(b) - 25) <= ratio_thresh * 25

    b = s[2]
    assert abs(b[0] - 200) <= thresh
    assert abs(b[1] - 350) <= thresh
    assert abs(radius(b) - 45) <= ratio_thresh * 45

    # Testing no peaks
    img_empty = np.zeros((100, 100), dtype=dtype)
    assert blob_dog(img_empty).size == 0
Beispiel #5
0
def test_blob_dog():
    r2 = math.sqrt(2)
    img = np.ones((512, 512))

    xs, ys = circle(400, 130, 5)
    img[xs, ys] = 255

    xs, ys = circle(100, 300, 25)
    img[xs, ys] = 255

    xs, ys = circle(200, 350, 45)
    img[xs, ys] = 255

    blobs = blob_dog(img, min_sigma=5, max_sigma=50)
    radius = lambda x: r2 * x[2]
    s = sorted(blobs, key=radius)
    thresh = 5

    b = s[0]
    assert abs(b[0] - 400) <= thresh
    assert abs(b[1] - 130) <= thresh
    assert abs(radius(b) - 5) <= thresh

    b = s[1]
    assert abs(b[0] - 100) <= thresh
    assert abs(b[1] - 300) <= thresh
    assert abs(radius(b) - 25) <= thresh

    b = s[2]
    assert abs(b[0] - 200) <= thresh
    assert abs(b[1] - 350) <= thresh
    assert abs(radius(b) - 45) <= thresh

    # Testing no peaks
    img_empty = np.zeros((100,100))
    assert blob_dog(img_empty).size == 0

    # Testing 3D
    r = 10
    pad = 10
    im3 = ellipsoid(r, r, r)
    im3 = util.pad(im3, pad, mode='constant')

    blobs = blob_dog(im3, min_sigma=3, max_sigma=10,
                          sigma_ratio=1.2, threshold=0.1)
    b = blobs[0]

    assert b[0] == r + pad + 1
    assert b[1] == r + pad + 1
    assert b[2] == r + pad + 1
    assert abs(math.sqrt(3) * b[3] - r) < 1
Beispiel #6
0
def blob_image_multiscale2(image, type=0, scale=2):
    # function that return a list of blob_coordinates, 0 = dog, 1 = doh, 2 = log
    list = []
    image = norm.normalize(image)
    for z, slice in tqdm(enumerate(image)):
        # init list of different sigma/zoom blobs
        featureblobs = []
        # x = 0,1,2,3,4
        if scale == 2:
            # for x in xrange(0,6):
            #     if type == 0:
            #         featureblobs.append(feature.blob_dog(slice, 2**x, 2**x))
            #     if type == 1:
            #         featureblobs.append(feature.blob_doh(slice, 2**x, 2**x))
            #     if type == 2:
            #         featureblobs.append(feature.blob_log(slice, 2**x, 2**x))
            for x in xrange(0, 5):
                if type == 0:
                    featureblobs.append(
                        feature.blob_dog(slice, 2**x, 2**(x + 1)))
                if type == 1:
                    featureblobs.append(
                        feature.blob_doh(slice, 2**x, 2**(x + 1)))
                if type == 2:
                    featureblobs.append(
                        feature.blob_log(slice, 2**x, 2**(x + 1), 16, .1))
        else:
            for x in xrange(0, 4):
                if type == 0:
                    featureblobs.append(feature.blob_dog(slice, 3**x, 3**x))
                if type == 1:
                    featureblobs.append(feature.blob_doh(slice, 3**x, 3**x))
                if type == 2:
                    featureblobs.append(feature.blob_log(slice, 3**x, 3**x))
        # init list of blob coords
        blob_coords = []
        #print featureblobs
        # start at biggest blob size
        for featureblob in reversed(featureblobs):
            # for every blob found of a blobsize

            for blob in enumerate(featureblob):
                # if that blob is not within range of another blob, add it
                blob = blob[1]
                if not within_range(blob, blob_coords):
                    blob_coords.append([z, blob[0], blob[1], blob[2]])
        list.append(blob_coords)
    return list
Beispiel #7
0
def autoFind(win, centerList, ringsList, colors, labels):
    """runs autofind method to get all the rings with their sizes. for now, 
    everything is treated as a general ring"""

    #get the image, convert it to greyscale, and invert it
    image = io.imread(imageName)
    grey = color.rgb2grey(image)
    grey_inv = util.invert(grey)

#    image_width = len(grey)
#    image_height = len(grey[0])
    
        
    #Find blobs in image and then get the centers from those
    blobs = feature.blob_dog(grey_inv, min_sigma=0.03, max_sigma=30, 
                             sigma_ratio=2.8, threshold=0.8, overlap=0.5)
    centers = getBlobCenters(blobs)
    
    #convert centers to graphical object points and add to centerList
    for center in centers:
        centerList[2].append(graphics.Point(center[0], center[1]))
    
    #create a general ring at each point
    for centerPt in centerList[2]:
        ring = Ring(win, centerPt, 10, colors[2], labels[2])
        ringsList.append(ring)
Beispiel #8
0
def get_areas_interest(width, height):
    widthRatio = 1024.0 / width
    heightRatio = 1024.0 / height

    img_arr = np.array(Image.open('screenshot.png'), dtype=np.uint8)
    image_gray = rgb2gray(img_arr)

    # get mines
    mine_blobs = blob_log(image_gray,
                          max_sigma=30,
                          num_sigma=10,
                          threshold=.05)
    mine_blobs[:, 2] = mine_blobs[:, 2] * sqrt(2)
    mines = mine_blobs[(mine_blobs[:, 2] > 5.5) & (mine_blobs[:, 2] < 7)]
    mines[:, 0] /= widthRatio
    mines[:, 1] /= heightRatio
    mines[:, 2] /= max(widthRatio, heightRatio)

    # get worm holes
    blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.3)
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)
    worm_holes = blobs_dog[(blobs_dog[:, 2] > 12)]
    worm_holes[:, 0] /= widthRatio
    worm_holes[:, 1] /= heightRatio
    worm_holes[:, 2] /= max(widthRatio, heightRatio)

    return mines, worm_holes
Beispiel #9
0
def _snap():
    cam = VideoCapture(2)  # 0 -> index of camera
    s, img = cam.read()
    if s:
        imsave('snap.jpg', img)
        ax.clear()
    image = imread('snap.jpg')
    ax.imshow(image)
    #Inverse the grayscale image
    #image_gray = rgb2gray(image)
    image_gray = cvtColor(image, COLOR_BGR2GRAY)
    image_gray = 1 - (rgb2gray(image))
    #Compute the blobs and estimate size
    blobs_dog = blob_dog(image_gray,
                         max_sigma=w2.get() / 1.,
                         threshold=w.get() / 200.)
    blobs_dog[:, 2] = blobs_dog[:, 2] * np.sqrt(2)
    #Plot circles
    i = 0
    for row in blobs_dog:
        y, x, r = row
        c = plt.Circle((x, y), r, color='lime', linewidth=2, fill=False)
        ax.add_patch(c)
        i = i + 1
        ax.annotate(str(i), xy=(2, 2), xytext=(x, y), color=(0.9, 0, 0.9))
    ax.annotate('Number of blobs = ' + (str(i)),
                xy=(2, 2),
                xytext=(20, 40),
                color=(0.1, 0.1, 0.1),
                backgroundcolor='white')
    ax.set_axis_off()
    canvas.show()
Beispiel #10
0
def find_blob(img, meta, directory, smaller = 1, largest = 5, thresh = 60, plot=True, save=False):
    #threshold = int((threshold_otsu(img)*thresh)/100)

    blobs = blob_dog(img,  min_sigma=smaller,
                     max_sigma=largest, threshold=thresh)
    if plot == True:
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 10))
        ax1.imshow(np.amax(img,axis=0), vmax=img.max()/1.8)
        ax2.imshow(np.amax(img,axis=0), vmax=img.max()/1.8)
        for blob in blobs:
            z,x,y,s = blob
            loci = ax2.scatter(y, x, s=40, facecolors='none', edgecolors='y')
        if save:
            try:
                filename = meta['Name']+"FOCI"+'.pdf'
                plt.savefig(directory+'/'+filename, transparent=True)
            except FileNotFoundError:
                plt.savefig(filename, transparent=True)
    elif plot ==False:
        plt.ioff()
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 10))
        ax1.imshow(np.amax(img,axis=0), vmax=img.max()/1.8)
        ax2.imshow(np.amax(img,axis=0), vmax=img.max()/1.8)
        for blob in blobs:
            z,x,y,s = blob
            loci = ax2.scatter(y, x, s=40, facecolors='none', edgecolors='y')
        if save:
            try:
                filename = meta['Name']+"_FOCI"+'.pdf'
                plt.savefig(directory+'/'+filename, transparent=True)
            except FileNotFoundError:
                plt.savefig(filename, transparent=True)
        plt.close(fig)

    return blobs
Beispiel #11
0
def test_blob_dog_3d(dtype, threshold_type):
    # Testing 3D
    r = 10
    pad = 10
    im3 = ellipsoid(r, r, r)
    im3 = np.pad(im3, pad, mode='constant')

    if threshold_type == 'absolute':
        threshold = 0.001
        threshold_rel = 0
    elif threshold_type == 'relative':
        threshold = 0
        threshold_rel = 0.5

    blobs = blob_dog(
        im3,
        min_sigma=3,
        max_sigma=10,
        sigma_ratio=1.2,
        threshold=threshold,
        threshold_rel=threshold_rel,
    )
    b = blobs[0]

    assert b.shape == (4, )
    assert b[0] == r + pad + 1
    assert b[1] == r + pad + 1
    assert b[2] == r + pad + 1
    assert abs(math.sqrt(3) * b[3] - r) < 1.1
def test_blob_dog():
    img = np.ones((512, 512))

    xs, ys = circle(400, 130, 5)
    img[xs, ys] = 255

    xs, ys = circle(100, 300, 25)
    img[xs, ys] = 255

    xs, ys = circle(200, 350, 45)
    img[xs, ys] = 255

    blobs = blob_dog(img, min_sigma=5, max_sigma=50)
    area = lambda x: x[2]
    radius = lambda x: math.sqrt(x / math.pi)
    s = sorted(blobs, key=area)
    thresh = 5

    b = s[0]
    assert abs(b[0] - 400) <= thresh
    assert abs(b[1] - 130) <= thresh
    assert abs(radius(b[2]) - 5) <= thresh

    b = s[1]
    assert abs(b[0] - 100) <= thresh
    assert abs(b[1] - 300) <= thresh
    assert abs(radius(b[2]) - 25) <= thresh

    b = s[2]
    assert abs(b[0] - 200) <= thresh
    assert abs(b[1] - 350) <= thresh
    assert abs(radius(b[2]) - 45) <= thresh
Beispiel #13
0
def test_blob_dog_3d_anisotropic(dtype, threshold_type):
    # Testing 3D anisotropic
    r = 10
    pad = 10
    im3 = ellipsoid(r / 2, r, r)
    im3 = np.pad(im3, pad, mode='constant')

    if threshold_type == 'absolute':
        threshold = 0.001
        threshold_rel = None
    elif threshold_type == 'relative':
        threshold = None
        threshold_rel = 0.5

    blobs = blob_dog(
        im3.astype(dtype, copy=False),
        min_sigma=[1.5, 3, 3],
        max_sigma=[5, 10, 10],
        sigma_ratio=1.2,
        threshold=threshold,
        threshold_rel=threshold_rel,
    )
    b = blobs[0]

    assert b.shape == (6, )
    assert b[0] == r / 2 + pad + 1
    assert b[1] == r + pad + 1
    assert b[2] == r + pad + 1
    assert abs(math.sqrt(3) * b[3] - r / 2) < 1.1
    assert abs(math.sqrt(3) * b[4] - r) < 1.1
    assert abs(math.sqrt(3) * b[5] - r) < 1.1
Beispiel #14
0
def detector(fyle):
    img = io.imread(fyle)
    image_gray = rgb2gray((img))
    blobs_log = blob_dog(image_gray, max_sigma=30, threshold=.1)
    blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)
    blob_lyst = blobs_log
    return blob_lyst
def blobs(image, remove_mb = None, val = 160, size = 100):
    """ Convolve a kernel on the image and a gaussian filter to highligh blobs. Find blobs using the
    Difference of Gaussian. Remove from the list of blobs the blobs that are at the membrane.
    return 3 different list
    """

    thresh = threshold_otsu(image)

    #Find all the blobs in the image using Difference of Gaussian
    blobs_in_image = feature.blob_dog(image, min_sigma=0.01,
                        max_sigma=3, threshold=thresh)
    blob_list = []
    for blob in blobs_in_image:
        y, x, r = blob
        blob_list.append((y, x))



    if remove_mb == None:
        blob_in_image_after_binary = set(blob_list)

    else:
        #Create a mask to remove blobs that are at the membrane and surrounded
        #by bright big object
        binary = image >= val*thresh/100
        binary = dilation(binary, square(3))
        binary = remove_small_objects(binary, min_size=size)
        # Create a list of coordinate with the binary image
        coor_binary = np.nonzero(binary)
        list_blob_masked = zip(*coor_binary)
        #Substract the list of coordinate from the binary image to the list of blobs
        blob_in_image_after_binary = (set(blob_list) - set (list_blob_masked))

    return blob_in_image_after_binary
Beispiel #16
0
def dog(image,
        mask=None,
        intensity='dark',
        min_sigma=1,
        max_sigma=50,
        sigma_ratio=2,
        threshold=0.1,
        overlap=1):
    if mask is None:
        mask = np.ones_like(image)
    im = check_blob_intensity(image, intensity, show=False)
    try:
        blobs = skifea.blob_dog(im,
                                min_sigma=min_sigma,
                                max_sigma=max_sigma,
                                sigma_ratio=sigma_ratio,
                                threshold=threshold,
                                overlap=overlap)
    except:
        return []
    if len(blobs) > 0:
        blobs[:, 2] = blobs[:, 2] * math.sqrt(2)
        blobs = np.round(blobs).astype(np.int)
        blobs = [x for x in blobs if mask[x[0], x[1]]]
    return blobs
Beispiel #17
0
 def dog(self):
     """Difference of Gaussian."""
     # skimage.feature.blob_dog(image, min_sigma=1, max_sigma=50,
     #     sigma_ratio=1.6, threshold=2.0, overlap=0.5)
     blobs = feature.blob_dog(self.image, **self.blob_ka, **self.dog_ka)
     blobs[:, 2] = blobs[:, 2] * sqrt(2)  # Compute radii in 3rd column.
     return blobs
Beispiel #18
0
def create_blob_sequence(image):
    """
    Apply multiple blob detection algorithms to compare them
    
    :param image: image to be analysed
    :return: squenece containing the blobs, colors and titles
    """
    blobs_log = blob_log(image,
                         min_sigma=15,
                         max_sigma=40,
                         num_sigma=10,
                         overlap=1)

    # Compute radii in the 3rd column.
    blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)

    blobs_dog = blob_dog(image, min_sigma=5, max_sigma=40, overlap=1)
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)

    blobs_doh = blob_doh(image, min_sigma=5, max_sigma=40, overlap=1)

    blobs_list = [blobs_log, blobs_dog, blobs_doh]
    colors = ["yellow", "green", "black", "blue"]
    titles = [
        "Laplacian of Gaussian",
        "Difference of Gaussian",
        "Determinant of Hessian",
    ]
    sequence = zip(blobs_list, colors, titles)

    return sequence
Beispiel #19
0
def featurize(img_name):
    """Load an image and convert it into a dictionary of features"""
    img = plt.imread(os.path.join('stimuli', img_name + '.png'))
    height, width, _ = img.shape
    features = defaultdict(int)
    for y in range(height):
        for x in range(width):
            features['red'] += img[y][x][0]
            features['green'] += img[y][x][1]
            features['blue'] += img[y][x][2]
            features['alpha'] += img[y][x][3]

    grey = color.rgb2grey(img)
    for y in range(height):
        for x in range(width):
            for key, value in per_pixel(grey, y, x):
                features[key] += value

    # Normalize over image size
    for key, value in features.items():
        features[key] = float(value) / height / width

    features['blob'] = feature.blob_dog(grey).shape[0]
    features['corners'] = feature.corner_peaks(
        feature.corner_harris(grey)).shape[0]
    return features
def blob_detector(img, min_sigma=1, max_sigma=8, threshold=0.4, overlap=0.1):
    blobs_dog = feature.blob_dog(img,
                                 min_sigma=min_sigma,
                                 max_sigma=max_sigma,
                                 threshold=threshold,
                                 overlap=overlap)
    return (blobs_dog)
def blobs(image, remove_mb=None, val=160, size=100):
    """ Convolve a kernel on the image and a gaussian filter to highligh blobs. Find blobs using the
    Difference of Gaussian. Remove from the list of blobs the blobs that are at the membrane.
    return 3 different list
    """

    thresh = threshold_otsu(image)

    #Find all the blobs in the image using Difference of Gaussian
    blobs_in_image = feature.blob_dog(image,
                                      min_sigma=0.01,
                                      max_sigma=3,
                                      threshold=thresh)
    blob_list = []
    for blob in blobs_in_image:
        y, x, r = blob
        blob_list.append((y, x))

    if remove_mb == None:
        blob_in_image_after_binary = set(blob_list)

    else:
        #Create a mask to remove blobs that are at the membrane and surrounded
        #by bright big object
        binary = image >= val * thresh / 100
        binary = dilation(binary, square(3))
        binary = remove_small_objects(binary, min_size=size)
        # Create a list of coordinate with the binary image
        coor_binary = np.nonzero(binary)
        list_blob_masked = zip(*coor_binary)
        #Substract the list of coordinate from the binary image to the list of blobs
        blob_in_image_after_binary = (set(blob_list) - set(list_blob_masked))

    return blob_in_image_after_binary
def detect_cells(image):
    image_gray = rgb2gray(image)

    blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1)
    # Compute radii in the 3rd column.
    blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)

    blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1)
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)

    blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01)

    blobs_list = [blobs_log, blobs_dog, blobs_doh]
    colors = ['yellow', 'lime', 'red']
    titles = ['Laplacian of Gaussian', 'Difference of Gaussian',
          'Determinant of Hessian']
    sequence = zip(blobs_list, colors, titles)

    for blobs, color, title in sequence:
        fig, ax = plt.subplots(1, 1)
        ax.set_title(title)
        ax.imshow(image, interpolation='nearest')
        for blob in blobs:
            y, x, r = blob
            c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False)
            ax.add_patch(c)

    plt.show()
def difference_of_gaussians_2D(file_names,
                               scale,
                               min_sig=2,
                               max_sig=20,
                               thrsh=0.02):
    global xpixlength
    global ypixlength
    plots = []
    blobs = []
    print('starting loop')
    pix_dimage = ndimage.imread(file_names[0], flatten=True)
    ypixlength = len(pix_dimage[0])
    xpixlength = len(pix_dimage)
    for name in file_names:
        image = ndimage.imread(name, flatten=True)
        image = block_reduce(image, block_size=(scale, scale), func=np.mean)
        plots.append(image.tolist())
        image = (image - np.min(image)) / np.max(image)
        tempblobs = blob_dog(image,
                             max_sigma=max_sig,
                             min_sigma=min_sig,
                             threshold=thrsh,
                             overlap=0).tolist()
        for tempblob in tempblobs:
            tempblob.append(0)
            tempblob.append(0)
        if tempblobs == []:
            blobs.append([[]])
        else:
            blobs.append(tempblobs)
        print(name)
    return blobs, plots
Beispiel #24
0
def test_blob_dog():
    r2 = math.sqrt(2)
    img = np.ones((512, 512))
    img3 = np.ones((5, 5, 5))

    xs, ys = circle(400, 130, 5)
    img[xs, ys] = 255

    xs, ys = circle(100, 300, 25)
    img[xs, ys] = 255

    xs, ys = circle(200, 350, 45)
    img[xs, ys] = 255

    blobs = blob_dog(img, min_sigma=5, max_sigma=50)
    radius = lambda x: r2 * x[2]
    s = sorted(blobs, key=radius)
    thresh = 5

    b = s[0]
    assert abs(b[0] - 400) <= thresh
    assert abs(b[1] - 130) <= thresh
    assert abs(radius(b) - 5) <= thresh

    b = s[1]
    assert abs(b[0] - 100) <= thresh
    assert abs(b[1] - 300) <= thresh
    assert abs(radius(b) - 25) <= thresh

    b = s[2]
    assert abs(b[0] - 200) <= thresh
    assert abs(b[1] - 350) <= thresh
    assert abs(radius(b) - 45) <= thresh

    assert_raises(ValueError, blob_dog, img3)
Beispiel #25
0
def blob_detections(image):
    
    image_gray = rgb2gray(image).astype('float64')/255
    
    blobs_log = blob_log(1-image_gray, max_sigma=20, num_sigma=10, threshold=0.15)
    
    # Compute radii in the 3rd column.
    blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)
    
    blobs_dog = blob_dog(1-image_gray, max_sigma=20, threshold=0.5)
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)
    
    blobs_doh = blob_doh(1-image_gray, max_sigma=20, threshold=.002)
    
    blobs_list = [blobs_log, blobs_dog, blobs_doh]
    colors = ['yellow', 'lime', 'red']
    titles = ['Laplacian of Gaussian', 'Difference of Gaussian',
              'Determinant of Hessian']
    sequence = zip(blobs_list, colors, titles)
    
    fig, axes = plt.subplots(1, 3, figsize=(9, 3), sharex=True, sharey=True,
                             subplot_kw={'adjustable': 'box-forced'})
    ax = axes.ravel()
    
    for idx, (blobs, color, title) in enumerate(sequence):
        ax[idx].set_title(title)
        ax[idx].imshow(image, interpolation='nearest', cmap='gray')
        for blob in blobs:
            y, x, r = blob
            c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False)
            ax[idx].add_patch(c)
        ax[idx].set_axis_off()
    
    plt.tight_layout()
    plt.show()
Beispiel #26
0
def find_peaks_dog(z, min_sigma=1., max_sigma=50., sigma_ratio=1.6,
                   threshold=0.2, overlap=0.5, exclude_border=False):
    """
    Finds peaks via the difference of Gaussian Matrices method from
    `scikit-image`.

    Parameters
    ----------
    z : numpy.ndarray
        2-d array of intensities
    float min_sigma, max_sigma, sigma_ratio, threshold, overlap
        Additional parameters to be passed to the algorithm. See `blob_dog`
        documentation for details:
        http://scikit-image.org/docs/dev/api/skimage.feature.html#blob-dog

    Returns
    -------
    numpy.ndarray
        Array of peak coordinates of shape `(n_peaks, 2)`

    Notes
    -----
    While highly effective at finding even very faint peaks, this method is
    sensitive to fluctuations in intensity near the edges of the image.

    """
    from skimage.feature import blob_dog
    z = z / np.max(z)
    blobs = blob_dog(z, min_sigma=min_sigma, max_sigma=max_sigma,
                     sigma_ratio=sigma_ratio, threshold=threshold,
                     overlap=overlap)

    centers = blobs[:, :2]
    return centers
    def find_blocks(self):

        final_grid = gaussian(np.copy(self.occupancy_grid), sigma=0.2)

        final_grid[final_grid > 0.95] = 1
        final_grid[final_grid <= 0.95] = 0

        rr, cc = rectangle_perimeter((1, 1), (78, 78), shape=final_grid.shape)
        final_grid[rr, cc] = 0

        rr, cc = rectangle((1, 1), (13, 13), shape=final_grid.shape)
        final_grid[rr, cc] = 0

        rr, cc = rectangle((1, 65), (13, 78), shape=final_grid.shape)
        final_grid[rr, cc] = 0

        final_grid = gaussian(final_grid, sigma=0.4)

        self.detected_blocks = blob_dog((final_grid),
                                        min_sigma=1.5,
                                        max_sigma=2.3,
                                        threshold=0.01,
                                        overlap=0.4)

        return final_grid, self.detected_blocks
Beispiel #28
0
def count_blob(img):
    img = reader(img)
    bw = img.mean(axis=2)
    blobs_dog = [(x[0], x[1], x[2]) for x in feature.blob_dog(
        -bw, min_sigma=2, max_sigma=8, threshold=0.0001, overlap=0.6)]
    blobs_dog = set(blobs_dog)
    return str(len(blobs_dog))
Beispiel #29
0
def blob_counter(img, min_sigma=2, max_sigma=8, treshold=0.0001, overlap=0.6):
    img = imread(img, as_grey=True)
    bw = img.mean(axis=2)
    blobs_dog = [(x[0], x[1], x[2]) for x in feature.blob_dog(
        -bw, min_sigma=2, max_sigma=8, threshold=0.0001, overlap=0.6)]
    blobs_dog = set(blobs_dog)
    return str(len(blobs_dog))
Beispiel #30
0
    def circles(self, filename):
        image = cv2.imread(filename, 0)
        image_gray = rgb2gray(image)

        blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1)

        # Compute radii in the 3rd column.
        blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)

        blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1)
        blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)

        blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01)

        blobs_list = [blobs_log, blobs_doh]
        colors = ['yellow', 'red']
        titles = ['Laplacian of Gaussian', 'Determinant of Hessian']
        sequence = zip(blobs_list, colors, titles)

        fig, axes = plt.subplots(1, 2, sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'})
        axes = axes.ravel()

        for blobs, color, title in sequence:
            ax = axes[0]
            axes = axes[1:]
            ax.set_title(title)
            ax.imshow(image, interpolation='nearest')
            for blob in blobs:
                y, x, r = blob
                c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False)
                ax.add_patch(c)

        plt.savefig('output.png')
        plt.show()
Beispiel #31
0
    def find_blocks(self):
        ''' finds blocks using the current occupancy grid
		args: 
			None
		returns:
			numpy array: final grid - final grid showing detections
			list: detected_blocks - list of detected blocks
		'''

        final_grid = gaussian(np.copy(self.occupancy_grid), sigma=0.2)

        final_grid[final_grid > 0.95] = 1
        final_grid[final_grid <= 0.95] = 0

        rr, cc = rectangle_perimeter((1, 1), (78, 78), shape=final_grid.shape)
        final_grid[rr, cc] = 0

        rr, cc = rectangle((1, 1), (13, 13), shape=final_grid.shape)
        final_grid[rr, cc] = 0

        rr, cc = rectangle((1, 65), (13, 78), shape=final_grid.shape)
        final_grid[rr, cc] = 0

        final_grid = gaussian(final_grid, sigma=0.4)

        self.detected_blocks = blob_dog((final_grid),
                                        min_sigma=1.5,
                                        max_sigma=2.3,
                                        threshold=0.01,
                                        overlap=0.4)

        return final_grid, self.detected_blocks
Beispiel #32
0
def test_blob_dog_2d(shape, blobs, min_sigma, max_sigma, sigma_ratio, overlap,
                     threshold):
    a = generate_blobimage(shape, blobs)
    chunks = [e // 2 for e in shape]
    d = da.from_array(a, chunks=chunks)
    ski_r = ski_feat.blob_dog(
        a,
        min_sigma=min_sigma,
        max_sigma=max_sigma,
        sigma_ratio=sigma_ratio,
        threshold=threshold,
        overlap=overlap,
    )

    print(ski_r)
    da_r = da_feat.blob_dog(
        d,
        min_sigma=min_sigma,
        max_sigma=max_sigma,
        sigma_ratio=sigma_ratio,
        threshold=threshold,
        overlap=overlap,
    )

    ski_r = sort_array(ski_r)
    da_r = sort_array(da_r)
    dau.assert_eq(ski_r, da_r)
Beispiel #33
0
def detect_blobs(original_image, processed_image, max_sigma=30, threshold=0.1):
    """
    Detects bright blobs in an image using the scikit-image
    determinant of gaussian technique, then marks them on the
    image.
    
    Input: original and processed images; max_sigma to determine 
    upper limit for blob size; threshold to determine how bright
    something needs to be before it's identified as a blob.
    
    Output: displays image with red rings around detected blobs;
    returns array of blob markers (y,x,radius).
    """

    blobs_dog = feature.blob_dog(processed_image,
                                 max_sigma=max_sigma,
                                 threshold=threshold)
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)  #radius calcs
    fig, axes = plt.subplots(ncols=3, figsize=(16, 12))
    ax_im_pairs = list(
        zip(axes, (original_image, processed_image, original_image),
            (False, True, True)))
    for ax, im, draw in ax_im_pairs:
        ax.imshow(im)
        if draw == True:
            for blob in blobs_dog:
                y, x, r = blob
                c = plt.Circle((x, y), r, color='r', linewidth=2, fill=False)
                ax.add_patch(c)
    print("{} blobs detected.".format(len(blobs_dog)))

    return blobs_dog
Beispiel #34
0
def find_blobs(img):
    #@Jon start here: Blobs might work, but should instead start with Ale's coordinates, and just find the z-slice where the mean signal is highest. Then use that to calculate distance within a nucleus
    # input = channel image that corresponds to same volume of an individual nucleus
    print("this is find blobs")
    blobs = blob_dog(img, max_sigma=10, threshold=0.01)
    print("done with blob_log")
    if len(blobs) > 1:
        print(blobs)

        ### Blob test
        blobs[:, 2] = blobs[:, 2] * math.sqrt(3)
        color = 'lime'
        fig, ax = plt.subplots(1, 1)

        ax.imshow(exposure.equalize_adapthist(img), cmap='gray')

        for blob in blobs:
            y, x, r = blob

            c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False)
            ax.add_patch(c)
            ax.set_axis_off()

        plt.tight_layout()
        plt.show()

        input('Press enter to continue')
        plt.close()
    else:
        print("no blobs")
Beispiel #35
0
def hlpr(image):
    image = data.hubble_deep_field()[0:500, 0:500]
    image_gray = rgb2gray(image)

    blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1)
    # Compute radii in the 3rd column.
    blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)

    blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1)
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)

    blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01)

    blobs_list = [blobs_log, blobs_dog, blobs_doh]
    colors = ['yellow', 'lime', 'red']
    titles = [
        'Laplacian of Gaussian', 'Difference of Gaussian',
        'Determinant of Hessian'
    ]
    sequence = zip(blobs_list, colors, titles)

    for blobs, color, title in sequence:
        fig, ax = plt.subplots(1, 1)
        ax.set_title(title)
        ax.imshow(image, interpolation='nearest')
        for blob in blobs:
            y, x, r = blob
            c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False)
            ax.add_patch(c)

    plt.show()
Beispiel #36
0
def test_blob_dog():
    r2 = math.sqrt(2)
    img = np.ones((512, 512))
    img3 = np.ones((5, 5, 5))

    xs, ys = circle(400, 130, 5)
    img[xs, ys] = 255

    xs, ys = circle(100, 300, 25)
    img[xs, ys] = 255

    xs, ys = circle(200, 350, 45)
    img[xs, ys] = 255

    blobs = blob_dog(img, min_sigma=5, max_sigma=50)
    radius = lambda x: r2 * x[2]
    s = sorted(blobs, key=radius)
    thresh = 5

    b = s[0]
    assert abs(b[0] - 400) <= thresh
    assert abs(b[1] - 130) <= thresh
    assert abs(radius(b) - 5) <= thresh

    b = s[1]
    assert abs(b[0] - 100) <= thresh
    assert abs(b[1] - 300) <= thresh
    assert abs(radius(b) - 25) <= thresh

    b = s[2]
    assert abs(b[0] - 200) <= thresh
    assert abs(b[1] - 350) <= thresh
    assert abs(radius(b) - 45) <= thresh

    assert_raises(ValueError, blob_dog, img3)
Beispiel #37
0
def count(image, value, im, plot_):
    """count the number of panels within an image using difference of Gaussian
    blob detection"""
    darkremove(value, image)
    # Load image and transform to a 2D numpy array
    depth = tuple(image.shape)[2]
    assert depth == 3
    # Ask user to input image scale size to create correct 'blob' sizes
    min_s, max_s = sigmas(float(input('What is the scale bar size of image ' + im +'? ')))
    # Convert the image to greyscale and invert to allow processing by algorithm
    grey = rgb2gray(image)
    grey = util.invert(grey)
    # Detect and count blobs
    blobs_dog = blob_dog(grey, min_sigma=min_s, max_sigma=max_s, threshold=.1, overlap=0.1)
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)
    blobs_area = []
    # Create plot overlaying blobs on image
    if plot_:
        fig = plt.figure(figsize=(15, 15))
        axis = fig.add_subplot(1, 1, 1)
        # Plot blobs
        axis.imshow(image, interpolation='nearest')
        for blob in blobs_dog:
            y, x, r = blob
            rect = plt.Rectangle(((x-r), (y-r)), 2*r, 2*r, color='yellow', linewidth=2, fill=False)
            blobs_area.append(np.pi*r**2)
            axis.add_patch(rect)
        axis.set_axis_off()
        plt.tight_layout()
        plt.show()
    return len(blobs_dog)
def doit(filename):
    dat = io.imread(filename)
    dat = rgb2gray(dat)

    blobs = blob_dog(dat, max_sigma=12, threshold=.25)
    blobs[:, 2] = blobs[:, 2] * (2 ** 0.5)

    io.imshow(dat)
    for blob in blobs:
        y, x, r = blob
        c = plt.Circle((x, y), r, color='r', linewidth=2, fill=False)
        plt.gca().add_patch(c)
    plt.show()

    print (blobs[:,2].size)

    r = (blobs[:,2])
    print (r)
    print (area_of_circle(r))
    avg_area = np.mean(area_of_circle(r))
    print (avg_area)
    
    #Distance from average x 
    avg_x = np.mean(blobs[:,0])
    x = (blobs[:,0])
    x_dist = (x-avg_x)
    print (x_dist)
    
    #Distance from average y
    avg_y = np.mean(blobs[:,1])
    y = (blobs[:,1])
    y_dist = (y-avg_y)
    print (y_dist)
    
    return blobs # for potential further processing
Beispiel #39
0
    def precisionRecall(self):
        test_images = []
        test_blobs = []
        X = []
        Y_ground = []

        #Get blobs
        for i in range(500,505):
            file = self.croppedImages[i]
            iter_image = rgb2gray(cv2.imread(file))
            iter_blobs = blob_dog(iter_image, min_sigma=1, max_sigma=25,
                                  sigma_ratio=1.6, threshold=.25, overlap=0.5)
            test_images.append(iter_image)
            test_blobs.append(iter_blobs)
            print("Get blobs: " + str(i) + "/1000")

        #Get X values for testing
        for i in range(0, len(test_images)):
            RadPic = self.RadPIC(10, test_blobs[i], rgb2gray(test_images[i]))
            inputHOG = self.HOG(10, test_blobs[i], rgb2gray(test_images[i]))
            X.extend(self.makeX(RadPic, inputHOG))
            print("X: " + str(i) + "/1000")

        #Get Y ground truth values
        for i in range(500, 505):
            j = i
            tempStr = self.labels[j]

            while tempStr.find("frame" + str(i)) == -1:
                j = j + 1
                tempStr = self.labels[j]

            label_image = cv2.imread((glob.glob(tempStr))[0])
            cropped_image = cv2.imread((glob.glob("cropped_images/frame" + str(i) + ".jpg"))[0])
            cropped_image = rgb2gray(cropped_image)
            blobs = blob_doh(cropped_image, min_sigma=1, max_sigma=25, num_sigma=15, threshold=.001)
            for blob in blobs:
                y, x, r = blob
                if label_image[y,x][0] == 255 & label_image[y,x][1] == 255 & label_image[y,x][2] == 255:
                    Y_ground.append(1)
                else:
                    Y_ground.append(0)
                #print("Ground Truth: " + str(i) + "/1000")

        #Open classifier
        with open('croppedImagesV2.pkl', 'rb') as f:
            forest = pickle.load(f)

        #Precidicions
        Y_classifier = forest.predict(X)

        #Precision-Recall
        precision, recall, thresholds = precision_recall_curve(Y_ground, Y_classifier)

        plt.plot(recall, precision)
        plt.ylabel('Precision')
        plt.xlabel('Recall')
        plt.show()
Beispiel #40
0
def blob_image_multiscale2(image, type=0,scale=2):
    # function that return a list of blob_coordinates, 0 = dog, 1 = doh, 2 = log
    list = []
    image = norm.normalize(image)
    for z, slice in tqdm(enumerate(image)):
        # init list of different sigma/zoom blobs
        featureblobs = []
        # x = 0,1,2,3,4
        if scale == 2:
            # for x in xrange(0,6):
            #     if type == 0:
            #         featureblobs.append(feature.blob_dog(slice, 2**x, 2**x))
            #     if type == 1:
            #         featureblobs.append(feature.blob_doh(slice, 2**x, 2**x))
            #     if type == 2:
            #         featureblobs.append(feature.blob_log(slice, 2**x, 2**x))
            for x in xrange(0,5):
                if type == 0:
                    featureblobs.append(feature.blob_dog(slice, 2**x, 2**(x+1)))
                if type == 1:
                    featureblobs.append(feature.blob_doh(slice, 2**x, 2**(x+1)))
                if type == 2:
                    featureblobs.append(feature.blob_log(slice, 2**x, 2**(x+1),16,.1))
        else:
            for x in xrange(0,4):
                if type == 0:
                    featureblobs.append(feature.blob_dog(slice, 3**x, 3**x))
                if type == 1:
                    featureblobs.append(feature.blob_doh(slice, 3**x, 3**x))
                if type == 2:
                    featureblobs.append(feature.blob_log(slice, 3**x, 3**x))
        # init list of blob coords
        blob_coords = []
        #print featureblobs
        # start at biggest blob size
        for featureblob in reversed(featureblobs):
            # for every blob found of a blobsize

            for blob in enumerate(featureblob):
                # if that blob is not within range of another blob, add it
                blob = blob[1]
                if not within_range(blob, blob_coords):
                    blob_coords.append([z, blob[0], blob[1], blob[2]])
        list.append(blob_coords)
    return list
Beispiel #41
0
    def process(self, img2, image_gray):
        # img2 = warp(img2)
        patch_size = [640]
        img2 = rgb2gray(img2)
        image_gray = rgb2gray(img2)

        blobs_dog = blob_dog(image_gray, min_sigma=0.2, max_sigma=225, sigma_ratio=1.6, threshold=.5)
        blobs_dog[:, 2] = blobs_dog[:, 2]

        blobs = [blobs_dog]
        colors = ['black']
        titles = ['Difference of Gaussian']
        sequence = zip(blobs, colors, titles)

        # plt.imshow(img2)
        # plt.axis("equal")
        # plt.show()

        for blobs, color, title in sequence:
            print(len(blobs))
            for blob in blobs:
                y, x, r = blob
                plotx = x
                ploty = y
                for i in range (3):
                    keypoints1 = corner_peaks(corner_harris(Array.image_arr[i]), min_distance=1)
                    keypoints2 = corner_peaks(corner_harris(img2), min_distance=1)

                    extractor = BRIEF(patch_size=30, mode="uniform")

                    extractor.extract(Array.image_arr[i], keypoints1)
                    keypoints1 = keypoints1[extractor.mask]
                    descriptors1 = extractor.descriptors

                    extractor.extract(img2, keypoints2)
                    keypoints2 = keypoints2[extractor.mask]
                    descriptors2 = extractor.descriptors

                    matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True)
                    
                    # print(keypoints1, keypoints2)
                    # print(matches12)
                    #FUCKGGGPLAYT
                    for pizdezh in matches12:
                        X = keypoints2[pizdezh[1]][1]
                        Y = keypoints2[pizdezh[1]][0]

                    if sqrt((plotx - X)**2 + (ploty - Y)**2) < r:
                        seen = [{
                            "type": Array.type_arr[i],
                            "center_shift": (plotx - 160/2) * -0.02,
                            "distance": image_gray[y][x] / 0.08
                        }]
                        print seen
                        data.seen.add(seen)
                        break
 def get_blobs(self, image):
   blobs_log = blob_log(image, max_sigma=30, num_sigma=10, threshold=.1)
   blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)
   blobs_dog = blob_dog(image, max_sigma=30, threshold=.1)
   blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)
   blobs_doh = blob_doh(image, max_sigma=30, threshold=.01)
   
   all_blobs = np.vstack([blobs_log, blobs_doh, blobs_dog])
   all_blobs = filter(lambda b: b[2] > 4, all_blobs)
   all_blobs = list(filter(lambda b: b[2] < 60, all_blobs))
   return all_blobs
Beispiel #43
0
def test_blob_dog():
    r2 = math.sqrt(2)
    img = np.ones((512, 512))
    img3 = np.ones((5, 5, 5))

    xs, ys = circle(400, 130, 5)
    img[xs, ys] = 255

    xs, ys = circle(100, 300, 25)
    img[xs, ys] = 255

    xs, ys = circle(200, 350, 45)
    img[xs, ys] = 255

    blobs = blob_dog(img, min_sigma=5, max_sigma=50)
    radius = lambda x: r2 * x[2]
    s = sorted(blobs, key=radius)
    thresh = 5

    b = s[0]
    assert abs(b[0] - 400) <= thresh
    assert abs(b[1] - 130) <= thresh
    assert abs(radius(b) - 5) <= thresh

    b = s[1]
    assert abs(b[0] - 100) <= thresh
    assert abs(b[1] - 300) <= thresh
    assert abs(radius(b) - 25) <= thresh

    b = s[2]
    assert abs(b[0] - 200) <= thresh
    assert abs(b[1] - 350) <= thresh
    assert abs(radius(b) - 45) <= thresh

    with pytest.raises(ValueError):
        blob_dog(img3)

    # Testing no peaks
    img_empty = np.zeros((100,100))
    assert blob_dog(img_empty).size == 0
def getBlobs(data, zDim, nChan, medFiltSize=7):

  sElem = np.ones((medFiltSize,medFiltSize), dtype=np.uint8)


  blobs = dict.fromkeys (  [(z,c) for z in range(zDim) for c in range(nChan)] )
  for z,c in blobs.keys():
    print z,c
    temp = filters.median( data[z,c,:,:] , sElem)
    blobs[(z,c)]  = blob_dog(temp, max_sigma=30, min_sigma=5, threshold=0.2, sigma_ratio=1.4)


  return blobs
def extract(image):
	
    # used with default parameters, play around with params for other results
    blob_dog_feature = blob_dog(image, min_sigma=1, max_sigma=50, sigma_ratio=1.6, threshold=2.0, overlap=.5)

    # several sizes of radius, play around with params for other results
    hough_radii = np.array([5, 10, 15, 20, 30, 50])

    hough_circle_feature = hough_circle(image, hough_radii, normalize=True, full_output=False)

	# prints a LOT... takes a while
	# comment out the next line to print short version
    np.set_printoptions(threshold='nan')
    print([blob_dog_feature, hough_circle_feature])
    return [blob_dog_feature, hough_circle_feature]
def preprocess2(filename):
	fd_img = open(filename)
	img = Image.open(fd_img)
	img = resizeimage.resize('thumbnail', img, [512, 512])

	res = img = np.array(img)
	for k in range(len(img)):
		for j in range(len(img[0])):
			for i in range(3):
				s = sum(img[k][j])
				if s == 0:
					continue
				img[k][j][i] = 255 * img[k][j][i]/s
	img = color.rgb2gray(img)
	img = exposure.equalize_adapthist(img, clip_limit=0.03)
	#img = exposure.equalize_hist(img)
	top = 0
	bot = len(img)

	#print top,bot
	for i in range(len(img)):
		s = np.average(img[i,:])
		#print s
		if s > 0.1 and top == 0:
			top = i
		if s < 0.1 and top != 0 and bot == len(img[0]):
			bot = i-1
	#print "left:",top
	#print "right:",bot


	left = 0
	right = len(img[0])
	#print left,right
	for i in range(len(img[0])):
		s = np.average(img[:,i])
		#print s
		if s > 0.15 and left == 0:
			left = i
		if s < 0.15 and left != 0 and right == len(img[0]):
			right = i-1
	#print "left:",left
	#print "right:",right

	#img = img[top:bot,left:right]
	img = adapt(img)
	img = resize(img,(256,256))
	return blob_dog(img, min_sigma = 7, max_sigma=23, threshold=0.2, overlap=0.5)
Beispiel #47
0
def test(N,nd,log=False,cm=False):
    dx = []
    dy = []
    X =[]
    Y =[]
    Ddelta = []
    fail = 0
    for i in range(N):
        cx,cy = np.random.rand(2)
        rescale = lambda x: 2*(1-2*x)
        cx = rescale(cx)
        cy= rescale(cy)
        test = gaussian(10000,nd+cx,nd+cy,2,2)(*indices((2*nd+1,2*nd+1))) +500*np.random.rand(2*nd+1,2*nd+1)
        test= test-test.min()+0.01
        #test = np.array(test,dtype=np.float)
        tos=False
        if tos:
            figure()
            imshow(test)
        #print test
        blobs =  blob_dog(test,max_sigma=2,threshold=100)
        y0,x0,r = blobs[0]
        n=4
        #print blobs
        #imshow(test[y0-n:y0+n+1,x0-n:x0+n+1])
        try:
            params = fitgaussian(test[y0-n:y0+n+1,x0-n:x0+n+1]-test[y0-n:y0+n+1,x0-n:x0+n+1].min()+0.01,
                                 log=log,cm=cm)
            delta = test[y0-n:y0+n+1,x0-n:x0+n+1]-test[y0-n:y0+n+1,x0-n:x0+n+1].min()+0.01 -                         gaussian(*params)(*indices((2*n+1,2*n+1))) 
            Ddelta.append(np.std(delta))
            yp,xp=params[1:3]

            x = x0+xp-n
            y = y0+yp-n

            #print "d",nd+cx-x,nd+cy-y
            dx.append(nd+cx-x)
            dy.append(nd+cy-y)
            X.append(x)
            Y.append(y)
            if tos:
                plot([x],[y],"o","g")
                plot([nd+cx,nd+cy],"o","r")

        except:
            fail += 1
    print fail
    return X,Y,dx ,dy,np.std(dy),np.mean(Ddelta)
def visualize(image):
    blob_dog_feature = blob_dog(image, threshold=.1, max_sigma=10)
    max_y, max_x = image.shape
    image = color.gray2rgb(image)

    for item in blob_dog_feature:
        center_x, center_y, radius = item
        cx, cy = circle_perimeter(center_y, center_x, radius)

        # filtering out coordinates which are outside of the image
        cx, cy = zip(*filter(lambda (x, y): 0 <= x < max_x and 0 <= y < max_y, zip(cx, cy)))

        # make points red
        image[cy, cx] = (220, 20, 20)

    imshow(image)
    plt.show()
    def detect_blobs(self, min_sigma, max_sigma, num_sigma, threshold):
        blobs = []
        image_gray = rgb2gray(self.original_image)
        r, c = np.shape(image_gray)
        image_gray = image_gray[5:r-5,5:c-5]
        image_gray[1,1] = 1
        if self.method == 'log':
            blobs = blob_log(image_gray, min_sigma=min_sigma,
                             max_sigma=max_sigma, num_sigma=num_sigma, threshold=threshold)
            a = len(blobs[:])
            if a != 0:
                blobs[:, 2] = blobs[:, 2] * sqrt(2)

        elif self.method == 'dog':
            blobs = blobs_dog = blob_dog(image_gray, max_sigma=max_sigma, threshold=threshold)
            a = len(blobs[:])
            if a != 0:
                blobs[:, 2] = blobs[:, 2] * sqrt(2)
        else:
            blobs = blob_doh(image_gray, max_sigma=max_sigma, threshold=threshold)

        return blobs
Beispiel #50
0
def show_eyeballs(work_im):
    work_im = invert(work_im)
    work_im = gaussian_filter(work_im, 1.2)

    seed = np.copy(work_im)
    seed[1:-1, 1:-1] = work_im.min()
    mask = work_im

    dilated = reconstruction(seed, mask, method='dilation')

    image = work_im - dilated

    blobs_dog = None
    try:
        blobs_dog = blob_dog(image, min_sigma=5, max_sigma=10, threshold=.6)
    except:
        return None
    if blobs_dog.shape[0] == 0 or blobs_dog.shape[0] == 0:
        return None
    blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)

    return blobs_dog
from matplotlib import pyplot as plt
from skimage import data
from skimage.feature import blob_dog, blob_log, blob_doh
from math import sqrt
from skimage.color import rgb2gray

# image = data.hubble_deep_field()[0:500, 0:500]
image = cv2.resize(img1, (256, 256))
image_gray = rgb2gray(image)

blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=0.1)
# Compute radii in the 3rd column.
blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)

blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=0.1)
blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)

blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=0.01)

blobs_list = [blobs_log, blobs_dog, blobs_doh]
colors = ["yellow", "lime", "red"]
titles = ["Laplacian of Gaussian", "Difference of Gaussian", "Determinant of Hessian"]
sequence = zip(blobs_list, colors, titles)

for blobs, color, title in sequence:
    fig, ax = plt.subplots(1, 1)
    ax.set_title(title)
    ax.imshow(image, interpolation="nearest")
    for blob in blobs:
        y, x, r = blob
Beispiel #52
0
#print np.amax(blurred_int)
bla = np.vstack((img,noisy,blurred))
io.imshow(bla)


#2nd Gaussian
from math import sqrt
img_2  = data.hubble_deep_field()
img_2  = img_2 [0:500,0:500]
io.imshow(img_2)
img_gray = color.rgb2gray(img_2)

blobs_log = feature.blob_log(img_gray, max_sigma=30, num_sigma=10, threshold=.1)
blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)

blobs_dog = feature.blob_dog(img_gray, max_sigma=30, threshold=.1)
blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)


def disp_blob(blobs,title):
    fig, ax = plt.subplots(1,1)
    ax.set_title(title)    
    ax.imshow(img_2, interpolation='nearest')
       

    for blob in blobs:        
        y, x, r = blob
        c = plt.Circle((x, y), r, color='yellow', linewidth=2, fill=False)
        ax.add_patch(c)

    return None
Beispiel #53
0
# In[265]:

if __name__ == "__main__":
    from skimage.feature import peak_local_max
    from scipy import ndimage
    lbl = ndimage.label(frame)[0]
    
    a = np.array([[0,0,0,0,0],
                 [0,1,1,1,0],
                 [0,1,3,1,0],
                 [0,1,2,1,0],
                 [0,0,0,0,0]],dtype=np.float)
#    a = np.array([[ 11123. , 14880. , 13101.],
# [ 11944.,  18426. , 15685.],
# [ 11506.  ,14961.  ,14082.]],dtype=np.float)
    blobs =  blob_dog(a,max_sigma=2,threshold=0.01)
    def cm(framep):
        print framep
        T = np.sum(framep)
        cx = np.sum(np.arange(framep.shape[0],dtype=np.float)*np.sum(framep,axis=1))/T
        cy = np.sum(np.arange(framep.shape[1],dtype=np.float)*np.sum(framep,axis=0))/T
        return cx,cy
    print blobs
    y0,x0,r = blobs[0]
    #y0,x0=1,1
    
    n=2
    params = fitgaussian(a[y0-n:y0+n+1,x0-n:x0+n+1],log=True)
    yp,xp=params[1:3]
    x = x0+xp-2
    y = y0+yp-2
Beispiel #54
0
def create_blobs(url, opt='all'):
    image = imread(url)
    return_dict = dict()
    print 'Image read: {}'.format(url)
    image_gray = rgb2gray(image)

    print 'Greyscale applied'

    if opt=='all':
        blobs_log = blob_log(image_gray, min_sigma=15, max_sigma=50, num_sigma=10, threshold=.1, overlap=0.8) 

        print 'Laplacian of Gaussian computed'
        # Compute radii in the 3rd column.
        blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)
        return_dict['LoG'] = blobs_log

        blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1)
        print 'Difference of Gaussian computed'

        blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2)
        return_dict['DoG'] = blobs_dog

        blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01)
        print 'Determinant of Hessian computed'

        return_dict['DoH'] = blobs_doh

        blobs_list = [blobs_log, blobs_dog, blobs_doh]
        colors = ['yellow', 'lime', 'red']
        titles = ['LoG', 'DoG',
                  'DoH']
        sequence = zip(blobs_list, colors, titles)
        print 'Sequence created'

    elif opt=='doh':
        print 'DoH only'
        blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01)
        return_dict['DoH'] = blobs_doh
        sequence = zip([blobs_doh], ['red'], ['DoH'])

    elif opt=='log':
        print 'LoG only'
        blobs_log = blob_log(image_gray, min_sigma=15, max_sigma=50, num_sigma=10, threshold=.1, overlap=0.8) 

        print 'Laplacian of Gaussian computed'
        # Compute radii in the 3rd column.
        blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)
        return_dict['LoG'] = blobs_log
        sequence = zip([blobs_log], ['yellow'], ['LoG'])
    print sequence
    
    fig,axes = plt.subplots(1, 3, sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})
    axes = axes.ravel()

    print 'Matplot initialized'
    print sequence
    for blobs, color, title in sequence:
        ax = axes[0]
        axes = axes[1:]
        ax.set_title(title)
        ax.imshow(image, interpolation='nearest')
        for blob in blobs:
            y, x, r = blob
            c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False)
            ax.add_patch(c)
    plt.show()
    return return_dict
#Stain space conversion
ihc_hrd = separate_stains(ihc_rgb, hrd_from_rgb)


'''DAB'''
#Rescale signals
#[:, :, 012 color]
dab_rescale = rescale_intensity(ihc_hrd[:, :, 2], out_range=(0, 1))
dab_array = np.dstack((np.zeros_like(dab_rescale), dab_rescale, dab_rescale))


#Blob detection
image2dD = rgb2grey(dab_array)


blobs_DoG_DAB = blob_dog(image2dD, min_sigma=1, max_sigma=25, threshold=.3, overlap=0.9)
blobs_DoG_DAB[:, 2] = blobs_DoG_DAB[:, 2] * sqrt(2)

blobs = [blobs_DoG_DAB]
colors = ['orange']
titles = ['Difference of Gaussian: DAB']
sequence = zip(blobs, colors, titles)

for blobs, color, title in sequence:
    fig, ax = plt.subplots(1, 1)
    ax.set_title(title)
    ax.imshow(image2dD, interpolation='nearest', cmap=plt.cm.gray)
    for blob in blobs:
        y, x, r = blob
        c = plt.Circle((x, y), r, color=color, linewidth=1, fill=False)
        ax.add_patch(c)
Beispiel #56
0
def detection(array, psf, bkg_sigma=5, mode='lpeaks', matched_filter=False,
              mask=True, snr_thresh=5, plot=True, debug=False,
              full_output=False, verbose=True, save_plot=None, plot_title=None,
              angscale=False, pxscale=0.01):
    """ Finds blobs in a 2d array. The algorithm is designed for automatically
    finding planets in post-processed high contrast final frames. Blob can be
    defined as a region of an image in which some properties are constant or
    vary within a prescribed range of values. See <Notes> below to read about
    the algorithm details.

    Parameters
    ----------
    array : array_like, 2d
        Input frame.
    psf : array_like
        Input psf, normalized with ``vip_hci.phot.normalize_psf``.
    bkg_sigma : int or float, optional
        The number standard deviations above the clipped median for setting the
        background level.
    mode : {'lpeaks','log','dog'}, optional
        Sets with algorithm to use. Each algorithm yields different results.
    matched_filter : bool, optional
        Whether to correlate with the psf of not.
    mask : bool, optional
        Whether to mask the central region (circular aperture of 2*fwhm radius).
    snr_thresh : float, optional
        SNR threshold for deciding whether the blob is a detection or not.
    plot : bool, optional
        If True plots the frame showing the detected blobs on top.
    debug : bool, optional
        Whether to print and plot additional/intermediate results.
    full_output : bool, optional
        Whether to output just the coordinates of blobs that fulfill the SNR
        constraint or a table with all the blobs and the peak pixels and SNR.
    verbose : bool, optional
        Whether to print to stdout information about found blobs.
    save_plot: string
        If provided, the plot is saved to the path.
    plot_title : str, optional
        Title of the plot.
    angscale: bool, optional
        If True the plot axes are converted to angular scale.
    pxscale : float, optional
        Pixel scale in arcseconds/px. Default 0.01 for Keck/NIRC2.

    Returns
    -------
    yy, xx : array_like
        Two vectors with the y and x coordinates of the centers of the sources
        (potential planets).
    If full_output is True then a table with all the candidates that passed the
    2d Gaussian fit constrains and their S/N is returned.

    Notes
    -----
    The FWHM of the PSF is measured directly on the provided array. If the
    parameter matched_filter is True then the PSF is used to run a matched
    filter (correlation) which is equivalent to a convolution filter. Filtering
    the image will smooth the noise and maximize detectability of objects with a
    shape similar to the kernel.
    The background level or threshold is found with sigma clipped statistics
    (5 sigma over the median) on the image/correlated image. Then 5 different
    strategies can be used to detect the blobs (potential planets):

    Local maxima + 2d Gaussian fit. The local peaks above the background on the
    (correlated) frame are detected. A maximum filter is used for finding local
    maxima. This operation dilates the original image and merges neighboring
    local maxima closer than the size of the dilation. Locations where the
    original image is equal to the dilated image are returned as local maxima.
    The minimum separation between the peaks is 1*FWHM. A 2d Gaussian fit is
    done on each of the maxima constraining the position on the subimage and the
    sigma of the fit. Finally the blobs are filtered based on its SNR.

    Laplacian of Gaussian + 2d Gaussian fit. It computes the Laplacian of
    Gaussian images with successively increasing standard deviation and stacks
    them up in a cube. Blobs are local maximas in this cube. LOG assumes that
    the blobs are again assumed to be bright on dark. A 2d Gaussian fit is done
    on each of the candidates constraining the position on the subimage and the
    sigma of the fit. Finally the blobs are filtered based on its SNR.

    Difference of Gaussians. This is a faster approximation of LoG approach. In
    this case the image is blurred with increasing standard deviations and the
    difference between two successively blurred images are stacked up in a cube.
    DOG assumes that the blobs are again assumed to be bright on dark. A 2d
    Gaussian fit is done on each of the candidates constraining the position on
    the subimage and the sigma of the fit. Finally the blobs are filtered based
    on its SNR.

    """
    def check_blobs(array_padded, coords_temp, fwhm, debug):
        y_temp = coords_temp[:,0]
        x_temp = coords_temp[:,1]
        coords = []
        # Fitting a 2d gaussian to each local maxima position
        for y, x in zip(y_temp, x_temp):
            subsi = 2 * int(np.ceil(fwhm))
            if subsi %2 == 0:
                subsi += 1
            subim, suby, subx = get_square(array_padded, subsi, y+pad, x+pad,
                                           position=True, force=True)
            cy, cx = frame_center(subim)

            gauss = models.Gaussian2D(amplitude=subim.max(), x_mean=cx,
                                      y_mean=cy, theta=0,
                                      x_stddev=fwhm*gaussian_fwhm_to_sigma,
                                      y_stddev=fwhm*gaussian_fwhm_to_sigma)

            sy, sx = np.indices(subim.shape)
            fitter = fitting.LevMarLSQFitter()
            fit = fitter(gauss, sx, sy, subim)

            # checking that the amplitude is positive > 0
            # checking whether the x and y centroids of the 2d gaussian fit
            # coincide with the center of the subimage (within 2px error)
            # checking whether the mean of the fwhm in y and x of the fit
            # are close to the FWHM_PSF with a margin of 3px
            fwhm_y = fit.y_stddev.value*gaussian_sigma_to_fwhm
            fwhm_x = fit.x_stddev.value*gaussian_sigma_to_fwhm
            mean_fwhm_fit = np.mean([np.abs(fwhm_x), np.abs(fwhm_y)])
            if fit.amplitude.value > 0 \
            and np.allclose(fit.y_mean.value, cy, atol=2) \
            and np.allclose(fit.x_mean.value, cx, atol=2) \
            and np.allclose(mean_fwhm_fit, fwhm, atol=3):
                coords.append((suby + fit.y_mean.value,
                               subx + fit.x_mean.value))

                if debug:
                    print('Coordinates (Y,X): {:.3f},{:.3f}'.format(y, x))
                    print('fit peak = {:.3f}'.format(fit.amplitude.value))
                    msg = 'fwhm_y in px = {:.3f}, fwhm_x in px = {:.3f}'
                    print(msg.format(fwhm_y, fwhm_x))
                    print('mean fit fwhm = {:.3f}'.format(mean_fwhm_fit))
                    pp_subplots(subim, colorb=True, axis=False, dpi=60)
        return coords

    def print_coords(coords):
        print('Blobs found:', len(coords))
        print(' ycen   xcen')
        print('------ ------')
        for i in range(len(coords[:, 0])):
            print('{:.3f} \t {:.3f}'.format(coords[i,0], coords[i,1]))

    def print_abort():
        if verbose:
            print(sep)
            print('No potential sources found')
            print(sep)

    # --------------------------------------------------------------------------

    if array.ndim != 2:
        raise TypeError('Input array is not a frame or 2d array')
    if psf.ndim != 2 and psf.shape[0] < array.shape[0]:
        raise TypeError('Input psf is not a 2d array or has wrong size')
        
    # Getting the FWHM from the PSF array
    cenpsf = frame_center(psf)
    outdf = fit_2dgaussian(psf, cent=(cenpsf), debug=debug, full_output=True)
    fwhm_x, fwhm_y = outdf['fwhm_x'], outdf['fwhm_y']
    fwhm = np.mean([fwhm_x, fwhm_y])
    if verbose:
        print('FWHM = {:.2f} pxs\n'.format(fwhm))
    if debug:
        print('FWHM_y', fwhm_y)
        print('FWHM_x', fwhm_x)

    # Masking the center, 2*lambda/D is the expected IWA
    if mask:
        array = mask_circle(array, radius=fwhm)

    # Matched filter
    if matched_filter:
        frame_det = correlate(array, psf)
    else:
        frame_det = array

    # Estimation of background level
    _, median, stddev = sigma_clipped_stats(frame_det, sigma=5, iters=None)
    bkg_level = median + (stddev * bkg_sigma)
    if debug:
        print('Sigma clipped median = {:.3f}'.format(median))
        print('Sigma clipped stddev = {:.3f}'.format(stddev))
        print('Background threshold = {:.3f}'.format(bkg_level))
        print()

    if mode == 'lpeaks' or mode == 'log' or mode == 'dog':
        # Padding the image with zeros to avoid errors at the edges
        pad = 10
        array_padded = np.lib.pad(array, pad, 'constant', constant_values=0)

    if debug and plot and matched_filter:
        print('Input frame after matched filtering:')
        pp_subplots(frame_det, rows=2, colorb=True)

    if mode == 'lpeaks':
        # Finding local peaks (can be done in the correlated frame)
        coords_temp = peak_local_max(frame_det, threshold_abs=bkg_level,
                                     min_distance=int(np.ceil(fwhm)),
                                     num_peaks=20)
        coords = check_blobs(array_padded, coords_temp, fwhm, debug)
        coords = np.array(coords)
        if verbose and coords.shape[0] > 0:
            print_coords(coords)

    elif mode == 'log':
        sigma = fwhm*gaussian_fwhm_to_sigma
        coords = feature.blob_log(frame_det.astype('float'),
                                  threshold=bkg_level,
                                  min_sigma=sigma-.5, max_sigma=sigma+.5)
        if len(coords) == 0:
            print_abort()
            return 0, 0
        coords = coords[:,:2]
        coords = check_blobs(array_padded, coords, fwhm, debug)
        coords = np.array(coords)
        if coords.shape[0] > 0 and verbose:
            print_coords(coords)

    elif mode == 'dog':
        sigma = fwhm*gaussian_fwhm_to_sigma
        coords = feature.blob_dog(frame_det.astype('float'),
                                  threshold=bkg_level, min_sigma=sigma-.5,
                                  max_sigma=sigma+.5)
        if len(coords) == 0:
            print_abort()
            return 0, 0
        coords = coords[:, :2]
        coords = check_blobs(array_padded, coords, fwhm, debug)
        coords = np.array(coords)
        if coords.shape[0] > 0 and verbose:
            print_coords(coords)

    else:
        msg = 'Wrong mode. Available modes: lpeaks, log, dog.'
        raise TypeError(msg)

    if coords.shape[0] == 0:
        print_abort()
        return 0, 0

    yy = coords[:, 0]
    xx = coords[:, 1]
    yy_final = []
    xx_final = []
    yy_out = []
    xx_out = []
    snr_list = []
    xx -= pad
    yy -= pad

    # Checking S/N for potential sources
    for i in range(yy.shape[0]):
        y = yy[i]
        x = xx[i]
        if verbose:
            print(sep)
            print('X,Y = ({:.1f},{:.1f})'.format(x,y))
        snr = snr_ss(array, (x,y), fwhm, False, verbose=False)
        snr_list.append(snr)
        if snr >= snr_thresh:
            if verbose:
                _ = frame_quick_report(array, fwhm, (x,y), verbose=verbose)
            yy_final.append(y)
            xx_final.append(x)
        else:
            yy_out.append(y)
            xx_out.append(x)
            if verbose:
                print('S/N constraint NOT fulfilled (S/N = {:.3f})'.format(snr))
            if debug:
                _ = frame_quick_report(array, fwhm, (x,y), verbose=verbose)

    if debug or full_output:
        table = Table([yy.tolist(), xx.tolist(), snr_list],
                      names=('y', 'x', 'px_snr'))
        table.sort('px_snr')
    yy_final = np.array(yy_final)
    xx_final = np.array(xx_final)
    yy_out = np.array(yy_out)
    xx_out = np.array(xx_out)

    if plot:
        coords = list(zip(xx_out.tolist() + xx_final.tolist(),
                          yy_out.tolist() + yy_final.tolist()))
        circlealpha = [0.3] * len(xx_out)
        circlealpha += [1] * len(xx_final)
        pp_subplots(array, circle=coords, circlealpha=circlealpha,
                    circlelabel=True, circlerad=fwhm, save=save_plot, dpi=120,
                    angscale=angscale, pxscale=pxscale, title=plot_title)

    if debug:
        print(table)

    if full_output:
        return table
    else:
        return yy_final, xx_final
Beispiel #57
0
def locate_blob(im):
    im2 = scipy.ndimage.gaussian_filter(im,0.3)
    blobs  = blob_dog(im2,max_sigma=20, threshold = 0.3)
    return blobs
Beispiel #58
0
def detection(array, psf, bkg_sigma=3, mode='lpeaks', matched_filter=True, 
              mask=True, snr_thresh=5, plot=True, debug=False, 
              full_output=False, verbose=True):                 
    """ Finds blobs in a 2d array. The algorithm is designed for automatically 
    finding planets in post-processed high contrast final frames. Blob can be 
    defined as a region of an image in which some properties are constant or 
    vary within a prescribed range of values. See <Notes> below to read about
    the algorithm details.
    
    Parameters
    ----------
    array : array_like, 2d
        Input frame.
    psf : array_like
        Input psf.
    bkg_sigma : float, optional
        The number standard deviations above the clipped median for setting the
        background level. 
    mode : {'lpeaks','irafsf','daofind','log','dog'}, optional
        Sets with algorithm to use. Each algorithm yields different results.
    matched_filter : {True, False}, bool optional
        Whether to correlate with the psf of not.
    mask : {True, False}, optional
        Whether to mask the central region (circular aperture of 2*fwhm radius).
    snr_thresh : float, optional
        SNR threshold for deciding whether the blob is a detection or not.         
    plot {True, False}, bool optional
        If True plots the frame showing the detected blobs on top.
    debug : {False, True}, bool optional
        Whether to print and plot additional/intermediate results.
    full_output : {False, True}, bool optional
        Whether to output just the coordinates of blobs that fulfill the SNR
        constraint or a table with all the blobs and the peak pixels and SNR.
    verbose : {True,False}, bool optional
        Whether to print to stdout information about found blobs.
    
    Returns
    -------
    yy, xx : array_like
        Two vectors with the y and x coordinates of the centers of the sources 
        (putative planets). 
    If full_output is True then a table with all the candidates that passed the
    2d Gaussian fit constrains and their SNR is returned. Also the count of 
    companions with SNR>5 (those with highest probability of being true 
    detections).
                
    Notes
    -----
    The PSF is used to run a matched filter (correlation) which is equivalent 
    to a convolution filter. Filtering the image will smooth the noise and
    maximize detectability of objects with a shape similar to the kernel. 
    The background level or threshold is found with sigma clipped statistics 
    (5 sigma over the median) on the image. Then 5 different strategies can be 
    used to detect the blobs (planets):
    
    Local maxima + 2d Gaussian fit. The local peaks above the background on the 
    (correlated) frame are detected. A maximum filter is used for finding local 
    maxima. This operation dilates the original image and merges neighboring 
    local maxima closer than the size of the dilation. Locations where the 
    original image is equal to the dilated image are returned as local maxima.
    The minimum separation between the peaks is 1*FWHM. A 2d Gaussian fit is 
    done on each of the maxima constraining the position on the subimage and the
    sigma of the fit. Finally an SNR criterion can be applied. 
    
    Laplacian of Gaussian. It computes the Laplacian of Gaussian images with 
    successively increasing standard deviation and stacks them up in a cube. 
    Blobs are local maximas in this cube. Detecting larger blobs is especially 
    slower because of larger kernel sizes during convolution. Only bright blobs 
    on dark backgrounds are detected. This is the most accurate and slowest 
    approach.
    
    Difference of Gaussians. This is a faster approximation of LoG approach. In 
    this case the image is blurred with increasing standard deviations and the 
    difference between two successively blurred images are stacked up in a cube. 
    This method suffers from the same disadvantage as LoG approach for detecting 
    larger blobs. Blobs are again assumed to be bright on dark.
    
    Irafsf. starfind algorithm (IRAF software) searches images for local density 
    maxima that have a peak amplitude greater than threshold above the local 
    background and have a PSF full-width half-maximum similar to the input fwhm. 
    The objects' centroid, roundness (ellipticity), and sharpness are calculated 
    using image moments.
    
    Daofind. Searches images for local density maxima that have a peak amplitude 
    greater than threshold (approximately; threshold is applied to a convolved 
    image) and have a size and shape similar to the defined 2D Gaussian kernel. 
    The Gaussian kernel is defined by the fwhm, ratio, theta, and sigma_radius 
    input parameters. Daofind finds the object centroid by fitting the the 
    marginal x and y 1D distributions of the Gaussian kernel to the marginal x 
    and y distributions of the input (unconvolved) data image.
                
    """
    def print_coords(coords):
        print 'Blobs found:', len(coords)
        print ' ycen   xcen'
        print '------ ------'
        for i in range(len(coords[:,0])):
            print ' ', coords[i,0], '\t', coords[i,1]
    
    if not array.ndim == 2:
        raise TypeError('Input array is not a frame or 2d array')
    if not psf.ndim == 2 and psf.shape[0] < array.shape[0]:
        raise TypeError('Input psf is not a 2d array or has wrong size')
    
    # Getting the FWHM with a 2d gaussian fit on the PSF
    gauss = Gaussian2D(amplitude=1, x_mean=5, y_mean=5, x_stddev=3.5, 
                       y_stddev=3.5, theta=0)
    fitter = LevMarLSQFitter()                  # Levenberg-Marquardt algorithm
    psf_subimage = get_square(psf, 9, frame_center(psf)[0],frame_center(psf)[1])
    y, x = np.indices(psf_subimage.shape)
    fit = fitter(gauss, x, y, psf_subimage)
    fwhm = np.mean([fit.y_stddev.value*gaussian_sigma_to_fwhm, 
                    fit.x_stddev.value*gaussian_sigma_to_fwhm])
    if verbose:  
        print 'FWHM =', fwhm
        print
    if debug:  
        print 'FWHM_y ', fit.y_stddev.value*gaussian_sigma_to_fwhm
        print 'FWHM_x ', fit.x_stddev.value*gaussian_sigma_to_fwhm  
        print
    
    # Masking the center, 2*lambda/D is the expected IWA
    if mask:  array = mask_circle(array, radius=2*fwhm)
    
    # Matched filter
    if matched_filter:  
        frame_det = correlate(array, psf)
    else:
        frame_det = array
    
    # Estimation of background level
    _, median, stddev = sigma_clipped_stats(frame_det, sigma=5, iters=None)
    bkg_level = median + (stddev * bkg_sigma)
    if debug:  
        print 'Sigma clipped median = {:.3f}'.format(median)
        print 'Sigma clipped stddev = {:.3f}'.format(stddev)
        print 'Background threshold = {:.3f}'.format(bkg_level)
        print
    
    round = 0.3   # roundness constraint
    
    # Padding the image with zeros to avoid errors at the edges
    pad = 10
    array_padded = np.lib.pad(array, pad, 'constant', constant_values=0)
        
    if debug and plot and matched_filter:  
        print 'Input frame after matched filtering'
        pp_subplots(frame_det, size=6, rows=2, colorb=True)
        
    if mode=='lpeaks':
        # Finding local peaks (can be done in the correlated frame)                                           
        coords_temp = peak_local_max(frame_det, threshold_abs=bkg_level, 
                                     min_distance=fwhm, num_peaks=20)
        y_temp = coords_temp[:,0]
        x_temp = coords_temp[:,1]
        coords = []
        # Fitting a 2d gaussian to each local maxima position
        for y,x in zip(y_temp,x_temp):
            subim, suby, subx = get_square(array_padded, 2*int(np.ceil(fwhm)), 
                                           y+pad, x+pad, position=True) 
            cy, cx = frame_center(subim)
            
            gauss = Gaussian2D(amplitude=subim.max(), 
                               x_mean=cx, y_mean=cy, 
                               x_stddev=fwhm*gaussian_fwhm_to_sigma, 
                               y_stddev=fwhm*gaussian_fwhm_to_sigma, theta=0)
            
            sy, sx = np.indices(subim.shape)
            fit = fitter(gauss, sx, sy, subim)
            
            # checking that the amplitude is positive > 0
            # checking whether the x and y centroids of the 2d gaussian fit 
            # coincide with the center of the subimage (within 2px error)
            # checking whether the mean of the fwhm in y and x of the fit are
            # close to the FWHM_PSF with a margin of 3px
            fwhm_y = fit.y_stddev.value*gaussian_sigma_to_fwhm
            fwhm_x = fit.x_stddev.value*gaussian_sigma_to_fwhm
            mean_fwhm_fit = np.mean([np.abs(fwhm_x), np.abs(fwhm_y)]) 
            if fit.amplitude.value>0 \
            and np.allclose(fit.y_mean.value, cy, atol=2) \
            and np.allclose(fit.x_mean.value, cx, atol=2) \
            and np.allclose(mean_fwhm_fit, fwhm, atol=3):                     
                coords.append((suby+fit.y_mean.value, subx+fit.x_mean.value))
        
            if debug:  
                print 'Coordinates (Y,X): {:.3f},{:.3f}'.format(y, x)
                print 'fit peak = {:.3f}'.format(fit.amplitude.value)
                #print fit
                msg = 'fwhm_y in px = {:.3f}, fwhm_x in px = {:.3f}'
                print msg.format(fwhm_y, fwhm_x) 
                print 'mean fit fwhm = {:.3f}'.format(mean_fwhm_fit)
                pp_subplots(subim, colorb=True)
        
        coords = np.array(coords)
        if verbose and coords.shape[0]>0:  print_coords(coords)
    
    elif mode=='daofind':                 
        tab = findstars.daofind(frame_det, fwhm=fwhm, threshold=bkg_level,
                                roundlo=-round,roundhi=round)
        coords = np.transpose((np.array(tab['ycentroid']), 
                               np.array(tab['xcentroid'])))
        if verbose:
            print 'Blobs found:', len(coords)
            print tab['ycentroid','xcentroid','roundness1','roundness2','flux']
                  
    elif mode=='irafsf':                
        tab = findstars.irafstarfind(frame_det, fwhm=fwhm, 
                                     threshold=bkg_level,
                                     roundlo=0, roundhi=round)
        coords = np.transpose((np.array(tab['ycentroid']), 
                               np.array(tab['xcentroid'])))
        if verbose:
            print 'Blobs found:', len(coords)
            print tab['ycentroid','xcentroid','fwhm','flux','roundness']
        
    elif mode=='log':
        sigma = fwhm*gaussian_fwhm_to_sigma
        coords = feature.blob_log(frame_det.astype('float'), 
                                  threshold=bkg_level, 
                                  min_sigma=sigma-.5, max_sigma=sigma+.5)
        coords = coords[:,:2]
        if coords.shape[0]>0 and verbose:  print_coords(coords)
     
    elif mode=='dog':
        sigma = fwhm*gaussian_fwhm_to_sigma
        coords = feature.blob_dog(frame_det.astype('float'), 
                                  threshold=bkg_level, 
                                  min_sigma=sigma-.5, max_sigma=sigma+.5)
        coords = coords[:,:2]
        if coords.shape[0]>0 and verbose:  print_coords(coords)
        
    else:
        msg = 'Wrong mode. Available modes: lpeaks, daofind, irafsf, log, dog.'
        raise TypeError(msg)

    if coords.shape[0]==0:
        if verbose:  
            print '_________________________________________'
            print 'No potential sources found'
            print '_________________________________________'
        return 0, 0
    
    yy = coords[:,0]
    xx = coords[:,1]
    yy_final = [] 
    xx_final = []
    yy_out = []
    xx_out = []
    snr_list = []
    px_list = []
    if mode=='lpeaks':
        xx -= pad
        yy -= pad
    
    # Checking SNR for potential sources
    for i in xrange(yy.shape[0]):
        y = yy[i] 
        x = xx[i] 
        if verbose: 
            print '_________________________________________'
            print 'Y,X = ({:.1f},{:.1f}) -----------------------'.format(y, x)
        subim = get_square(array, size=15, y=y, x=x)
        snr = snr_ss(array, y, x, fwhm, False, verbose=False)
        snr_list.append(snr)
        px_list.append(array[y,x])
        if snr >= snr_thresh and array[y,x]>0:
            if plot:
                pp_subplots(subim, size=2)
            if verbose:  
                _ = frame_quick_report(array, fwhm, y=y, x=x , verbose=verbose)
            yy_final.append(y)
            xx_final.append(x)
        else:
            yy_out.append(y)
            xx_out.append(x)
            if verbose:  print 'SNR constraint NOT fulfilled'
            if debug:
                if plot:
                    pp_subplots(subim, size=2)
                _ = frame_quick_report(array, fwhm, y=y, x=x , verbose=verbose)
            else:
                if verbose:  print 'SNR = {:.3f}'.format(snr)

    if debug or full_output:
        table = Table([yy.tolist(), xx.tolist(), px_list, snr_list], 
                      names=('y','x','px_val','px_snr'))
        table.sort('px_snr')
    yy_final = np.array(yy_final) 
    xx_final = np.array(xx_final) 
    yy_out = np.array(yy_out) 
    xx_out = np.array(xx_out) 
    
    if plot: 
        print
        print '_________________________________________'           
        print'Input frame showing all the detected blobs / potential sources'
        print 'In red circles those that did not pass the SNR and 2dGauss fit constraints'
        print 'In cyan circles those that passed the constraints'
        fig, ax = plt.subplots(figsize=(8,8))
        im = ax.imshow(array, origin='lower', interpolation='nearest', 
                       cmap='gray')
        colorbar_ax = fig.add_axes([0.92, 0.12, 0.03, 0.78])
        fig.colorbar(im, cax=colorbar_ax)
        ax.grid('off')
        
        for i in xrange(yy_out.shape[0]):
            y = yy_out[i]
            x = xx_out[i]
            circ = plt.Circle((x, y), radius=2*fwhm, color='red', fill=False,
                              linewidth=2)
            ax.text(x, y+5*fwhm, (int(y),int(x)), fontsize=10, color='red', 
                    family='monospace', ha='center', va='top', weight='bold')
            ax.add_patch(circ)
        for i in xrange(yy_final.shape[0]):
            y = yy_final[i]
            x = xx_final[i]
            circ = plt.Circle((x, y), radius=2*fwhm, color='cyan', fill=False, 
                              linewidth=2)
            ax.text(x, y+5*fwhm, (int(y),int(x)), fontsize=10, color='cyan', 
                    weight='heavy', family='monospace', ha='center', va='top')
            ax.add_patch(circ)
        plt.show()
    
    if debug:  print table
    
    if full_output:
        return table, yy_final.shape[0]
    else:
        return yy_final, xx_final
Beispiel #59
0
            #print(self.labels[i])

        #print(len(self.labels))
>>>>>>> c1b308ec15ebe3098d38e2f3bd0171bbd669606b
        if files == None:
            self.filenames = []
        else:
            self.filenames = files

            for i in range(0, len(self.filenames)):
<<<<<<< HEAD
                image = cv2.imread((glob.glob("cropped_images/*" + self.filenames[i]))[0])
                self.images.append(image)
                image_gray = rgb2gray(image)
                #blobs = blob_doh(image_gray, min_sigma=1, max_sigma=25, num_sigma=15, threshold=.001)
                blobs = blob_dog(image_gray, min_sigma=1, max_sigma=25, sigma_ratio=1.6, threshold=.25, overlap=0.5)
                if(len(blobs) != 0):
                    blobs[:, 2] = blobs[:, 2] * sqrt(2)

                self.all_blobs.append(blobs)
                file_processing = "Processing files: " + str(i+1) + "/" + str(len(self.filenames))
                #print("blobs size: ", len(blobs))
=======
                #image = cv2.imread(glob.glob("cropped_images/" + self.filenames[i]))
                #print("imageName: ", (glob.glob("cropped_images/" + self.filenames[i]))[0])
                image = cv2.imread((glob.glob("cropped_images/*" + self.filenames[i]))[0])
                self.images.append(image)
                image_gray = rgb2gray(image)
                #blobs = blob_doh(image_gray, min_sigma=3, max_sigma=35, num_sigma=30, threshold=.005)
                blobs = blob_doh(image_gray, min_sigma=1, max_sigma=25, num_sigma=15, threshold=.001)
                self.all_blobs.append(blobs)