def analyze_lowexp(self):
        try:
            summed = np.add(np.add(self.img[:, :, 0], self.img[:, :, 1]),
                            self.img[:, :, 2])

            smoothed = filters.gaussian(summed, 5)

            mask = cutoff(smoothed, self.specs)

            edges = filters.sobel(mask)

            # Detect two radii
            hough_radii = np.arange(CAPILLARY_DIAM_LOW_BOUND,
                                    CAPILLARY_DIAM_UP_BOUND, 2)
            hough_res = trans.hough_circle(edges, hough_radii)

            print('\tcalculating hough transform...')
            # Select the most prominent 1 circles
            accums, cx, cy, radii = trans.hough_circle_peaks(hough_res,
                                                             hough_radii,
                                                             total_num_peaks=1)
            self.cap_x = cx[0]
            self.cap_y = cy[0]
            self.cap_r = radii[0]

            # Detect two radii
            hough_radii = np.arange(self.specs[1], self.specs[2], 2)
            hough_res = trans.hough_circle(edges, hough_radii)

            # Select the most prominent 5 circles
            accums, cx, cy, radii = trans.hough_circle_peaks(hough_res,
                                                             hough_radii,
                                                             total_num_peaks=1)

            print("\tbore - accums, cx, cy, radii " +
                  str((accums, cx, cy, radii)))
            self.bore_x = cx[0]
            self.bore_y = cy[0]
            self.bore_r = radii[0]

            self.axes.imshow(self.img)
            self.axes.add_patch(
                Circle((self.bore_x, self.bore_y),
                       self.bore_r,
                       color='r',
                       fill=False))
            self.axes.add_patch(
                Circle((self.cap_x, self.cap_y),
                       self.cap_r,
                       color='r',
                       fill=False))

        except:
            raise ValueError("Failed during lowexp analysis of img: " +
                             str(self.name))
            raise
        ''' 
        ---------------------------- additional methods -----------------------
        '''
        """ 
    def analyze_otsu(self):
        try:
            # convert to grey
            grey = color.rgb2gray(self.img)

            #smooth to remove noise, high noise makes hough transform take significantly more time
            grey_smooth = filters.gaussian(grey, 3)

            # threshold via otsu histogram binning
            otsu = grey_smooth > filters.threshold_otsu(grey_smooth)

            # calculate edges via sobel method
            edges = filters.sobel(otsu)

            print('\tcalculating hough transform...')

            # Detect two radii
            hough_radii = np.arange(CAPILLARY_DIAM_LOW_BOUND,
                                    CAPILLARY_DIAM_UP_BOUND, 2)
            hough_res = trans.hough_circle(edges, hough_radii)

            # Select the most prominent circle
            accums, cx, cy, radii = trans.hough_circle_peaks(hough_res,
                                                             hough_radii,
                                                             total_num_peaks=1)
            self.cap_x = cx[0]
            self.cap_y = cy[0]
            self.cap_r = radii[0]

            # Detect two radii
            hough_radii = np.arange(self.specs[1], self.specs[2], 2)
            hough_res = trans.hough_circle(edges, hough_radii)

            # Select the most prominent circle
            accums, cx, cy, radii = trans.hough_circle_peaks(hough_res,
                                                             hough_radii,
                                                             total_num_peaks=1)
            print("\taccums, cx, cy, radii " + str((accums, cx, cy, radii)))
            self.bore_x = cx[0]
            self.bore_y = cy[0]
            self.bore_r = radii[0]

            self.axes.imshow(self.img)
            self.axes.set_title(str(self.name))
            self.axes.add_patch(
                Circle((self.bore_x, self.bore_y),
                       self.bore_r,
                       color='r',
                       fill=False))
            self.axes.add_patch(
                Circle((self.cap_x, self.cap_y),
                       self.cap_r,
                       color='r',
                       fill=False))

        except:
            raise ValueError("Failed during Otsu analysis of img: " +
                             str(self.name))
            raise
Esempio n. 3
0
def get_circle_locations(image, name, outputs, specs):
    try:
        summed = np.add(image[:,:,0], image[:,:,1])
        summed = np.add(summed, image[:,:,2])

        smoothed = filters.gaussian(summed, 5)       
        
        mask = cutoff(smoothed, specs)
#        plt.imshow(mask)
#        plt.show()
        
        edges = filters.sobel(mask)
        
        # Detect two radii
        hough_radii = np.arange(CAPILLARY_DIAM_LOW_BOUND, CAPILLARY_DIAM_UP_BOUND, 2)
        hough_res = trans.hough_circle(edges, hough_radii)
        
        # Select the most prominent 1 circles
        accums, cx, cy, radii = trans.hough_circle_peaks(hough_res, hough_radii,
                                                   total_num_peaks=1)
        cap_x = cx[0]
        cap_y = cy[0]
        cap_r = radii[0]
        
        # Detect two radii
        hough_radii = np.arange(specs[1], specs[2], 2)
        hough_res = trans.hough_circle(edges, hough_radii)
        
        # Select the most prominent 5 circles
        accums, cx, cy, radii = trans.hough_circle_peaks(hough_res, hough_radii,
                                                   total_num_peaks=1)
        print("accums, cx, cy, radii " + str( (accums, cx, cy, radii) ))
        bore_x = cx[0]
        bore_y = cy[0]
        bore_r = radii[0]
    
        fig1, ax1 = plt.subplots(ncols=1, nrows=1, figsize=(10, 4))
        ax1.imshow(image)
        ax1.add_patch(Circle((bore_x,bore_y),bore_r, color='r', fill=False))
        ax1.add_patch(Circle((cap_x,cap_y),cap_r, color='r', fill=False))
        fig1.savefig(outputs+'\\'+name[:-4]+'-circled.png')
        plt.close('all')
        return (cap_x, cap_y, cap_r), (bore_x,bore_y,bore_r)
    except: 
        print('failed at ' + str(name))
        print('expected outputs ' + str(outputs))
        print()
        raise
def find_circles(edge_img, min_radius, max_radius):
    hough_radii = np.arange(min_radius, max_radius, 2)
    hough_res = hough_circle(edge_img, hough_radii)
    accums, cx, cy, radii = hough_circle_peaks(hough_res,
                                               hough_radii,
                                               total_num_peaks=1)
    return list(zip(cy, cx, radii))
Esempio n. 5
0
def mid_phantom(image_ACR, imarray):
    # Detect edges in image
    edges = filters.canny(imarray,
                          sigma=3,
                          low_threshold=200,
                          high_threshold=1000)

    hough_radii = np.array([190 / 2 / image_ACR.PixelSpacing[1]])
    print type(edges)
    print type(hough_radii)
    hough_res = hough_circle(edges, hough_radii)

    # Detect contours and middle of phantom
    centers = []
    radii = []

    for radius, h in zip(hough_radii, hough_res):
        peaks = peak_local_max(h, num_peaks=1)
        centers.extend(peaks)
        radii.extend([radius, radius])

    center_x, center_y = centers[0]
    radius = radii[1]  # Niet nodig?
    radius = np.int32(radius)  # Niet nodig?
    cy, cx = circle_perimeter(center_y, center_x, radius)  # Niet nodig?
    return center_x, center_y, radii
Esempio n. 6
0
def _detect_nodes(edges, node_radius: Tuple[int, int], num_nodes: int, n):
    """
    """
    from skimage.transform import hough_circle, hough_circle_peaks
    from skimage import color
    from skimage.draw import circle_perimeter

    nodes = []

    hough_radii = np.arange(node_radius[0], node_radius[1], 1)
    hough_res = hough_circle(edges, hough_radii)
    accums, cx, cy, radii = hough_circle_peaks(hough_res,
                                               hough_radii,
                                               total_num_peaks=num_nodes)

    # fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 10))
    # image = color.gray2rgb(img.copy())
    i = 0
    for center_y, center_x, radius in zip(cy, cx, radii):
        # circy, circx = circle_perimeter(center_y, center_x, radius,
        #                                 shape=image.shape)
        # image[circy, circx] = (255, 20, 20)
        n.add_node(str(i),
                   x=center_x,
                   y=center_y,
                   r=radius,
                   coordinates=(center_x, -center_y))
        i += 1
Esempio n. 7
0
def find_circle(noisy_img, model):
    # Fill in this function
    noisy_img = np.expand_dims(np.expand_dims(noisy_img, axis=0), axis=-1)
    img = model.predict(noisy_img / np.amax(noisy_img)).reshape(IMAGE_SIZE, IMAGE_SIZE)

    edges = canny(img, low_threshold=0.5, high_threshold=1.0)
    try_radii = np.arange(10, MAX_RAD, 1)
    hough_res = hough_circle(edges, try_radii)
    _, cy, cx, radii = hough_circle_peaks(hough_res, try_radii, total_num_peaks=1)

    if cx.size == 0:
        cx = 0
    else:
        cx = cx[-1]
    if cy.size == 0:
        cy = 0
    else:
        cy = cy[-1]

    if radii.size == 0:
        radii = 0
    else:
        radii = radii[-1]

    return (cx, cy, radii)
Esempio n. 8
0
def GetCircles(I):
    Y = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)

    r_min = 50
    radius_list = np.arange(r_min, int(round(2.1 * r_min)))
    num_circles_per_scale = 50
    scale = 1.0
    pyramid = []
    circle_list = []
    while min(Y.shape[:2]) > r_min:
        M = canny(Y, sigma=2, low_threshold=10, high_threshold=20)
        # plt.imshow(M, cmap='gray')
        # plt.waitforbuttonpress()
        H = hough_circle(M, radius_list[radius_list < min(Y.shape[:2]) / 2])

        r_idx, y, x = np.unravel_index(
            H.reshape(-1).argsort()[::-1][:min(num_circles_per_scale, H.size)],
            H.shape)
        r = radius_list[r_idx]
        pyramid += [Y]
        circle_list += [
            np.array([scale * x, scale * y, scale * r, H[r_idx, y, x] / r]).T
        ]

        Y = cv2.resize(Y, (0, 0), fx=0.5, fy=0.5)
        scale *= 2.0
    circle_list = np.concatenate(circle_list)

    return circle_list
Esempio n. 9
0
def analyze_ra_rotation(rotate_fn):
    """ Get RA axis center of rotation XY coordinates

    Args:
        rotate_fn (str): FITS file of RA rotation

    Returns:
        tuple(int): A tuple of integers corresponding to the XY pixel position
        of the center of rotation around RA axis
    """
    d0 = fits.getdata(rotate_fn)  # - 2048

    # Get center
    position = (d0.shape[1] // 2, d0.shape[0] // 2)
    size = (1500, 1500)
    d1 = Cutout2D(d0, position, size)

    d1.data = d1.data / d1.data.max()

    # Get edges for rotation
    rotate_edges = canny(d1.data, sigma=1.0)

    rotate_hough_radii = np.arange(100, 500, 50)
    rotate_hough_res = hough_circle(rotate_edges, rotate_hough_radii)
    rotate_accums, rotate_cx, rotate_cy, rotate_radii = \
        hough_circle_peaks(rotate_hough_res, rotate_hough_radii, total_num_peaks=1)

    return d1.to_original_position((rotate_cx[-1], rotate_cy[-1]))
Esempio n. 10
0
def processImage(imgNumber = -1):
    if imgNumber > -1:
        greyimage = rgb2gray(io.imread("data/{img}.JPG".format(img=imgNumber)))
        greyimage = greyimage > .5
    else:
        greyimage = data.coins()


    image = img_as_ubyte(greyimage)
    edges = sobel(image)
    edges =  mp.dilation(canny(image, sigma=3, low_threshold=30, high_threshold=60))
    drawPlot(edges)

    # Detect two radii
    hough_radii = np.arange(100, 250, 20)
    hough_res = hough_circle(edges, hough_radii)

    # Select the most prominent 5 circles
    accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii,
                                           total_num_peaks=20)

    # Draw them
    image = color.gray2rgb(image)
    for center_y, center_x, radius in zip(cy, cx, radii):
        circy, circx = circle_perimeter(center_y, center_x, radius)
        image[circy, circx] = (220, 20, 20)

    drawPlot(image)
Esempio n. 11
0
def get_best_circles(mask, resize_factor=8):
    '''
    Get the best the best fit to a circle using the hough transform.
    '''
    #%%
    #resize image to increase speed. I don't want
    #%%
    min_size = min(mask.shape)
    resize_factor = min_size / max(128, min_size / resize_factor)
    dsize = tuple(int(x / resize_factor) for x in mask.shape[::-1])

    mask_s = cv2.dilate(mask, disk(resize_factor / 2))
    mask_s = cv2.resize(mask_s, dsize)
    #%%
    r_min = min(mask_s.shape)
    r_max = max(mask_s.shape)

    #use the first peak of the circle hough transform to initialize the food shape
    hough_radii = np.arange(r_min / 4, r_max / 2, 2)
    hough_res = hough_circle(mask_s, hough_radii)
    accums, cx, cy, radii = hough_circle_peaks(hough_res,
                                               hough_radii,
                                               total_num_peaks=9)
    #%%

    cx, cy, radii = [
        np.round(x * resize_factor).astype(np.int) for x in (cx, cy, radii)
    ]
    #%%

    return list(zip(accums, cx, cy, radii))
Esempio n. 12
0
def analyze_ra_rotation(rotate_fn):
    """ Get RA axis center of rotation XY coordinates

    Args:
        rotate_fn (str): FITS file of RA rotation

    Returns:
        tuple(int): A tuple of integers corresponding to the XY pixel position
        of the center of rotation around RA axis
    """
    d0 = fits.getdata(rotate_fn)  # - 2048

    # Get center
    position = (d0.shape[1] // 2, d0.shape[0] // 2)
    size = (1500, 1500)
    d1 = Cutout2D(d0, position, size)

    d1.data = d1.data / d1.data.max()

    # Get edges for rotation
    rotate_edges = canny(d1.data, sigma=1.0)

    rotate_hough_radii = np.arange(100, 500, 50)
    rotate_hough_res = hough_circle(rotate_edges, rotate_hough_radii)
    rotate_accums, rotate_cx, rotate_cy, rotate_radii = \
        hough_circle_peaks(rotate_hough_res, rotate_hough_radii, total_num_peaks=1)

    return d1.to_original_position((rotate_cx[-1], rotate_cy[-1]))
Esempio n. 13
0
def test_hough_circle():
    # Prepare picture
    img = np.zeros((120, 100), dtype=int)
    radius = 20
    x_0, y_0 = (99, 50)
    y, x = circle_perimeter(y_0, x_0, radius)
    img[x, y] = 1

    out1 = tf.hough_circle(img, radius)
    out2 = tf.hough_circle(img, [radius])
    assert_equal(out1, out2)
    out = tf.hough_circle(img, np.array([radius], dtype=np.intp))
    assert_equal(out, out1)
    x, y = np.where(out[0] == out[0].max())
    assert_equal(x[0], x_0)
    assert_equal(y[0], y_0)
Esempio n. 14
0
    def process(self, im):
        (width, height, _) = im.image.shape

        img_adapted = im.prep(self.transform)

        if width > self.max_resized or height > self.max_resized:
            scale_height = self.max_resized / height
            scale_width = self.max_resized / width
            scale = min(scale_height, scale_width)
            img_adapted = resize(img_adapted, (int(width * scale), int(height * scale)))

        edges = canny(img_adapted, sigma=self.sigma)

        # Detect two radii
        # Calculate image diameter
        shape = im.image.shape
        diam = math.sqrt(shape[0] ** 2 + shape[1] ** 2)
        radii = np.arange(diam / 3, diam * 0.8, 2)
        hough_res = hough_circle(edges, radii)

        accums = []
        for radius, h in zip(radii, hough_res):
            # For each radius, extract two circles
            peaks = peak_local_max(h, num_peaks=1, min_distance=1)
            if len(peaks) > 0:
                accums.extend(h[peaks[:, 0], peaks[:, 1]])

        if len(accums) == 0:  # TODO: fix, should not happen
            return [0]

        idx = np.argmax(accums)
        return [accums[idx]]
Esempio n. 15
0
def test_hough_circle_peaks_normalize():
    x_0, y_0, rad_0 = (50, 50, 20)
    img = np.zeros((120, 100), dtype=int)
    y, x = circle_perimeter(y_0, x_0, rad_0)
    img[x, y] = 1

    x_1, y_1, rad_1 = (60, 60, 30)
    y, x = circle_perimeter(y_1, x_1, rad_1)
    img[x, y] = 1

    radii = [rad_0, rad_1]
    hspaces = transform.hough_circle(img, radii)
    out = transform.hough_circle_peaks(hspaces,
                                       radii,
                                       min_xdistance=15,
                                       min_ydistance=15,
                                       threshold=None,
                                       num_peaks=np.inf,
                                       total_num_peaks=np.inf,
                                       normalize=False)

    # Two perfect circles are close but the second one is bigger.
    # Therefore, it is picked due to its high peak.
    assert_equal(out[1], np.array([y_1]))
    assert_equal(out[2], np.array([x_1]))
    assert_equal(out[3], np.array([rad_1]))
Esempio n. 16
0
def find_fingers_circles(edges, image, impy=None):

    hough_radii = np.arange(20, 60, 2)
    hough_res = hough_circle(edges, cv2.HOUGH_GRADIENT, hough_radii)

    centers = []
    accums = []
    radii = []

    for radius, h in zip(hough_radii, hough_res):
        # For each radius, extract two circles
        peaks = peak_local_max(h, num_peaks=5)
        centers.extend(peaks - hough_radii.max())
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius, radius])
    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))

    # Draw the most prominent 5 circles
    image = color.gray2rgb(edges)
    for idx in np.argsort(accums)[::-1][:5]:
        center_x, center_y = centers[idx]
        radius = radii[idx]
        cx, cy = circle_perimeter(center_y, center_x, radius)
        image[cy, cx] = (250, 0, 0)

    ax.imshow(image, cmap=plt.cm.gray)
    plt.show()
Esempio n. 17
0
    def blackout_outside(self, img, sigma=3):
        img_g = skic.rgb2gray(img)
        edges = skif.canny(img_g, sigma=sigma)

        hough_radii = np.arange(180, 210, 2)
        hough_res = skit.hough_circle(edges, hough_radii)

        centers = []
        accums = []
        radii = []

        for radius, h in zip(hough_radii, hough_res):
            # For each radius, extract two circles
            num_peaks = 1
            peaks = skif.peak_local_max(h, min_distance=40, num_peaks=num_peaks)
            if peaks != []:
                centers.extend(peaks)
                accums.extend(h[peaks[:, 0], peaks[:, 1]])
                radii.extend([radius] * num_peaks)

#                print radius, np.max(h.ravel()), len(peaks)

        if accums == [] and sigma==3:
            return self.blackout_outside(img, sigma=3)

    #     Draw the most prominent 5 circles
        image = (img.copy() / 4.0).astype(np.uint8)
        cx, cy = skid.circle(*self.average_hough_detections(hough_radii, hough_res))
        image[cy, cx] = img[cy, cx]

        return image
def electrode_detection(input_path, output_path):
    # approach one, using cv2
    img = cv.imread(input_path, 0)
    # Load picture and detect edges

    edges = canny(img, sigma=2, low_threshold=35, high_threshold=40)
    #plot the graph to get a better feeling
    """
    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 10))
    ax.imshow(edges, cmap=plt.cm.gray)
    plt.show()
    """
    # Detect circles with size of hough_radii
    hough_radii = np.arange(5, 40, 1)
    hough_res = hough_circle(edges, hough_radii)

    # Select the most prominent 30 circles
    accums, cx, cy, radii = hough_circle_peaks(hough_res,
                                               hough_radii,
                                               total_num_peaks=30)
    #this returns the list of points that are on the perimeters, and change the value to white
    #for better visualization

    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 10))
    for center_y, center_x, radius in zip(cy, cx, radii):
        circy, circx = circle_perimeter(center_y,
                                        center_x,
                                        radius,
                                        shape=img.shape)
        img[circy, circx] = 255
    ax.imshow(img, cmap=plt.cm.gray)
    plt.show()
    #np.save(output_path, list(zip(cy,cx)))
    np.savetxt(output_path, list(zip(cy, cx)), fmt='%s')
    return list(zip(cy, cx))
Esempio n. 19
0
def hough_fun(img):
	"""fit circles to segmented image based on plausible range of radii"""
	# based on screen shot, I'm guessing about 25px radius for now
	hough_radii = np.arange(28,45)
	hough_res = hough_circle(img, hough_radii)
	blank = img.copy()
	blank[::] = 0
	"""
	accum, cx, cy, rad = hough_circle_peaks(hough_res, hough_radii)
	for i, ac in enumerate(np.argsort(accum)[::-1][:10]):
		center_x = cx[i]
		center_y = cy[i]
		radius = rad[i]
		cx, cy = draw.circle_perimeter(center_y, center_x, radius)
		blank[cy, cx] = 255
	return blank
	"""
	# if can't import hough_circle_peaks, try to replicate:
	centers = []
	accums = []
	radii = []
	for radius, h in zip(hough_radii, hough_res):
	# For each radius, extract, say, 3 circles
		peaks = peak_local_max(h, num_peaks=2)
		centers.extend(peaks - hough_radii.max())
		accums.extend(h[peaks[:, 0], peaks[:, 1]])
		radii.extend([radius, radius])
	for idx in np.argsort(accums)[::-1][:25]:
		center_x, center_y = centers[idx]
		radius = radii[idx]
		cx, cy = draw.circle_perimeter(center_y, center_x, radius)
		blank[cy, cx] = 255
	return blank
Esempio n. 20
0
def detect_Hough(data):
    image = data.copy()
    edges = canny(image, sigma=10, low_threshold=60, high_threshold=90)

    # Detect circles between 80% and 100% of image semi-diagonal
    lx, ly = data.shape
    sizex, sizey = lx/2., ly/2.
    max_r = numpy.sqrt(sizex**2 + sizey**2) 
    hough_radii = numpy.linspace(0.5*max_r, 0.9 * max_r, 20)
    hough_res = hough_circle(edges, hough_radii)


    centers = []
    accums = []
    radii = []
    for radius, h in zip(hough_radii, hough_res):
        # For each radius, extract two circles
        num_peaks = 2
        peaks = peak_local_max(h, num_peaks=num_peaks)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * num_peaks)

    # Use the most prominent circle
    idx = numpy.argsort(accums)[::-1][:1]
    center_x, center_y = centers[idx]
    radius = radii[idx]
    return center_x, center_y, radius
Esempio n. 21
0
def circular_hough_transform(r1, r2, step, edge, peak_num):
    hough_radii = np.arange(r1, r2, step)
    hough_res = hough_circle(edge, hough_radii)
    accums, cx, cy, radii = hough_circle_peaks(hough_res,
                                               hough_radii,
                                               total_num_peaks=peak_num)
    return accums, cx, cy, radii
Esempio n. 22
0
    def _get_hough_circles(self):
        hough_radii = np.arange(self.radius_low, self.radius_high,
                                self.step)[::-1]
        hough_res = hough_circle(self.edges, hough_radii)
        centers = []
        accums = []
        radii = []  # For each radius, extract num_peaks circles
        num_peaks = 3
        for radius, h in zip(hough_radii, hough_res):
            peaks = peak_local_max(h, num_peaks=num_peaks)
            centers.extend(peaks)
            print 'circle centers = ', peaks
            accums.extend(h[peaks[:, 0], peaks[:, 1]])
            radii.extend([radius] * num_peaks)

        im = mpimg.imread(self.image_path)
        # crop image
        im = im[100:1000, 200:1100]
        for idx in np.arange(len(centers)):
            center_x, center_y = centers[idx]
            radius = radii[idx]
            cx, cy = circle_perimeter(center_y, center_x, radius)
            mask = (cx < im.shape[0]) * (cy < im.shape[1])
            im[cy[mask], cx[mask]] = (220., 20., 20.)
        return im
Esempio n. 23
0
def test_circles2():
    data = np.memmap("E:\\guts_tracking\\data\\fish202_aligned_masked_8bit_150x200x440.raw", dtype='uint8', shape=(440,200,150)).copy()

    i = 157

    hough_radii = np.arange(10, 100, 10)
    edges = feature.canny(data[i], sigma=3.0, low_threshold=0.4, high_threshold=0.8)
    hough_res = hough_circle(edges, hough_radii)

    centers = []
    accums = []
    radii = []

    for radius, h in zip(hough_radii, hough_res):
        peaks = feature.peak_local_max(h)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * len(peaks))

    image = ski.color.gray2rgb(data[i])

    for idx in np.argsort(accums)[::-1][:5]:
        center_x, center_y = centers[idx]
        radius = radii[idx]
        cx, cy = circle_perimeter(center_y, center_x, radius)

        if max(cx) < 150 and max(cy) < 200:
            image[cy, cx] = (220, 20, 20)

    plt.imshow(image, cmap='gray')

    plt.show()
Esempio n. 24
0
    def animate(i):
        print 'Frame %d' % i
        plt.title('Frame %d' % i)

        image = data[i]

        hough_radii = np.arange(10, 100, 10)
        edges = feature.canny(data[i], sigma=3.0, low_threshold=0.4, high_threshold=0.8)
        hough_res = hough_circle(edges, hough_radii)

        centers = []
        accums = []
        radii = []

        for radius, h in zip(hough_radii, hough_res):
            peaks = feature.peak_local_max(h)
            centers.extend(peaks)
            accums.extend(h[peaks[:, 0], peaks[:, 1]])
            radii.extend([radius] * len(peaks))

        image = ski.color.gray2rgb(data[i])

        for idx in np.argsort(accums)[::-1][:5]:
            center_x, center_y = centers[idx]
            radius = radii[idx]
            cx, cy = circle_perimeter(center_y, center_x, radius)

            if max(cx) < 150 and max(cy) < 200:
                image[cy, cx] = (220, 20, 20)

        im.set_data(image)

        return im,
Esempio n. 25
0
def test_hough_circle_peaks_total_peak():
    img = np.zeros((120, 100), dtype=int)

    x_0, y_0, rad_0 = (99, 50, 20)
    y, x = circle_perimeter(y_0, x_0, rad_0)
    img[x, y] = 1

    x_1, y_1, rad_1 = (49, 60, 30)
    y, x = circle_perimeter(y_1, x_1, rad_1)
    img[x, y] = 1

    radii = [rad_0, rad_1]
    hspaces = transform.hough_circle(img, radii)
    out = transform.hough_circle_peaks(hspaces,
                                       radii,
                                       min_xdistance=1,
                                       min_ydistance=1,
                                       threshold=None,
                                       num_peaks=np.inf,
                                       total_num_peaks=1)
    assert_equal(out[1][0], np.array([
        y_1,
    ]))
    assert_equal(out[2][0], np.array([
        x_1,
    ]))
    assert_equal(out[3][0], np.array([
        rad_1,
    ]))
Esempio n. 26
0
    def process(self, im):
        (width, height, _) = im.image.shape

        img_adapted = im.prep(self.transform)

        if width > self.max_resized or height > self.max_resized:
            scale_height = self.max_resized / height
            scale_width = self.max_resized / width
            scale = min(scale_height, scale_width)
            img_adapted = resize(img_adapted,
                                 (int(width * scale), int(height * scale)))

        edges = canny(img_adapted, sigma=self.sigma)

        # Detect two radii
        # Calculate image diameter
        shape = im.image.shape
        diam = math.sqrt(shape[0]**2 + shape[1]**2)
        radii = np.arange(diam / 3, diam * 0.8, 2)
        hough_res = hough_circle(edges, radii)

        accums = []
        for radius, h in zip(radii, hough_res):
            # For each radius, extract two circles
            peaks = peak_local_max(h, num_peaks=1, min_distance=1)
            if len(peaks) > 0:
                accums.extend(h[peaks[:, 0], peaks[:, 1]])

        if len(accums) == 0:  # TODO: fix, should not happen
            return [0]

        idx = np.argmax(accums)
        return [accums[idx]]
Esempio n. 27
0
def reshape_image(raw_patient):
    #generate pixels
    # approach one, using cv2
    img = cv2.imread(raw_patient, 0)
    # Load picture and detect edges
    edges = canny(img, sigma=3, low_threshold=10, high_threshold=50)
    # Detect two radii
    hough_radii = np.arange(200, 600, 1)
    hough_res = hough_circle(edges, hough_radii)
    # Select the most prominent 1 circles
    accums, cx, cy, radii = hough_circle_peaks(hough_res,
                                               hough_radii,
                                               total_num_peaks=1)
    mask_internal = np.zeros((2 * radii[0], 2 * radii[0]), dtype=np.uint8)
    y_min = cy[0] - radii[0]
    x_min = cx[0] - radii[0]

    #filtering the ones only in the pixels
    for y in range(0, (2 * radii[0])):
        for x in range(0, (2 * radii[0])):
            mask_internal[y, x] = img[y + y_min, x + x_min]

    # change the internal white pixels to black
    for y in range(0, (2 * radii[0])):
        for x in range(0, (2 * radii[0])):
            if mask_internal[y, x] >= white_pixel_min and mask_internal[
                    y, x] <= white_pixel_max:
                mask_internal[y, x] = black_pixel
    #np.save('Data/Modified_fluoro2/patient_'+str(i)+'.npy', mask_internal)
    return (mask_internal, (y_min, x_min), radii[0])
Esempio n. 28
0
def test_hough_circle_peaks_min_distance():
    x_0, y_0, rad_0 = (50, 50, 20)
    img = np.zeros((120, 100), dtype=int)
    y, x = circle_perimeter(y_0, x_0, rad_0)
    img[x, y] = 1

    x_1, y_1, rad_1 = (60, 60, 30)
    y, x = circle_perimeter(y_1, x_1, rad_1)
    # Add noise and create an imperfect circle to lower the peak in Hough space
    y[::2] += 1
    x[::2] += 1
    img[x, y] = 1

    x_2, y_2, rad_2 = (70, 70, 20)
    y, x = circle_perimeter(y_2, x_2, rad_2)
    # Add noise and create an imperfect circle to lower the peak in Hough space
    y[::2] += 1
    x[::2] += 1
    img[x, y] = 1

    radii = [rad_0, rad_1, rad_2]
    hspaces = transform.hough_circle(img, radii)
    out = transform.hough_circle_peaks(hspaces, radii, min_xdistance=15,
                                       min_ydistance=15, threshold=None,
                                       num_peaks=np.inf,
                                       total_num_peaks=np.inf,
                                       normalize=True)

    # The second circle is too close to the first one
    # and has a weaker peak in Hough space due to imperfectness.
    # Therefore it got removed.
    assert_equal(out[1], np.array([y_0, y_2]))
    assert_equal(out[2], np.array([x_0, x_2]))
    assert_equal(out[3], np.array([rad_0, rad_2]))
Esempio n. 29
0
def find_plate(img, radii_range):
    """
        Identifies the location of the plate
    """
    # Read image, and convert to floating point
    img = img_as_bool(imread(img, mode="F", flatten=True))

    # Detect edges
    edges = canny(img, sigma=2)

    # Find circles
    hough_radii = np.arange(radii_range[0], radii_range[1], 2)
    hough_res = hough_circle(edges, hough_radii)

    centers, accums, radii = [], [], []

    for radius, h in zip(hough_radii, hough_res):
        # For each radius, extract two circles
        num_peaks = 1
        peaks = peak_local_max(h, num_peaks=num_peaks)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * num_peaks)

    center = np.mean(centers, axis=0)
    radius = (sum(radii) * 1.0) / len(radii)
    return center, radius
Esempio n. 30
0
def find_inner_circle_parameters(plane_array, rmin=200, rmax=250):
    """Given a single planar image (e.g. a section from CT data), find the
    locations of the inner of two circles in the image."""

    xdim, ydim = plane_array.shape

    edges = find_edges_sobel(plane_array)

    hough_radii = np.arange(rmin, rmax, 3)
    hough_res = hough_circle(edges, hough_radii)

    # Find the two clearest circles
    c1, c2 = find_n_best_hough_circles(hough_radii, hough_res, 2)

    # Work out which is the inner circle
    r1 = c1[2]
    r2 = c2[2]
    if r1 > r2:
        inner_circle_radius = r2
        cx, cy, r = c2
    else:
        inner_circle_radius = r1
        cx, cy, r = c1

    return cx, cy, r
def find_circles(binary_patch):
    # Get size of the patch
    min_image_size = min(binary_patch.shape[0], binary_patch.shape[1])
    max_image_size = max(binary_patch.shape[0], binary_patch.shape[1])

    # Determine min and max radius based on patch size
    min_radius = max(10, int(min_image_size / 4))
    max_radius = int(max_image_size / 2)
    hough_radii = np.arange(min_radius, max_radius)

    # Apply Hough circle transform
    hough_res = hough_circle(binary_patch, hough_radii)

    # Set parameters for hough_circle_peaks
    min_distance = int(max_image_size / 3)
    threshold = 0.6
    num_peaks = np.inf
    total_num_peaks = 5
    normalize = True

    # Filter result of Hough circle transform based on parameters
    _, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, min_distance,
                                          min_distance, threshold, num_peaks,
                                          total_num_peaks, normalize)
    detected_circles = zip(cx, cy, radii)

    # Return found circles
    return detected_circles
Esempio n. 32
0
def hugh_circle_detection(image):
	# Load picture and detect edges
	edges = canny(image, sigma=3, low_threshold=10, high_threshold=50)

	fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(5, 2))

	# Detect two radii
	hough_radii = np.arange(15, 30, 2)
	hough_res = hough_circle(edges, hough_radii)

	centers = []
	accums = []
	radii = []

	for radius, h in zip(hough_radii, hough_res):
		# For each radius, extract two circles
		num_peaks = 2
		peaks = peak_local_max(h, num_peaks=num_peaks)
		centers.extend(peaks)
		accums.extend(h[peaks[:, 0], peaks[:, 1]])
		radii.extend([radius] * num_peaks)

	# Draw the most prominent 5 circles
	image = color.gray2rgb(image)
	for idx in np.argsort(accums)[::-1][:5]:
		center_x, center_y = centers[idx]
		radius = radii[idx]
		cx, cy = circle_perimeter(center_y, center_x, radius)
		image[cy, cx] = (220, 20, 20)

	ax.imshow(image, cmap=plt.cm.gray)
	plt.show()
Esempio n. 33
0
def find_plate2(path):
    # Load picture and detect edges
    image_rgb = io.imread(path)
    image = color.rgb2gray(image_rgb)
    # image = resize(image, (100, 100))
    image = rescale(image, 0.1)
    edges = canny(image, sigma=2, low_threshold=0.40, high_threshold=0.80)
    plt.imshow(edges)
    plt.show()
    # Detect two radii
    hough_radii = np.arange(20, 60, 2)
    hough_res = hough_circle(edges, hough_radii)

    # Select the most prominent 5 circles
    accums, cx, cy, radii = hough_circle_peaks(hough_res,
                                               hough_radii,
                                               total_num_peaks=3)

    # Draw them
    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4))
    image = color.gray2rgb(image)
    for center_y, center_x, radius in zip(cy, cx, radii):
        circy, circx = circle_perimeter(center_y, center_x, radius)
        try:
            image[circy, circx] = (220, 20, 20)
        except IndexError as e:
            print(e)

    ax.imshow(image, cmap=plt.cm.gray)
    plt.show()
Esempio n. 34
0
def analyze(FileName):

    img = io.imread(FileName)
    xc, yc, t = img.data.shape

    grayscale = rgb2gray(
        img
    )  # To use the later image analyis, the initial image must be converted to grayscale

    image = img_as_ubyte(
        grayscale[0:xc, 0:yc]
    )  # converts the image to a specific file format that can later be analysed
    # the array after 'grayscale' holds the size of the image.

    edges = canny(image,
                  sigma=3,
                  low_threshold=max_radius * .1,
                  high_threshold=max_radius *
                  .2)  # canny identifies any edges on the shape
    # sigma is required standard deviation, low and high threshold are the bounds for linking edges
    # It is recommended that you use 10% of the max possible cirlce size for the low_threshold and twice that for the high threshold

    h_radii = np.arange(
        min_radius, max_radius, 1
    )  # The first two are used to identify the high and low end of radii to search for
    # This will need to be adjusted as different files are uploaded.

    hough_res = hough_circle(
        edges, h_radii
    )  # function that calculates a 3D array where a very similar circle can live.
    # It takes in the number of pixels that will be used to create the

    print("Analysis almost complete...")

    accums, x, y, radius = hough_circle_peaks(
        hough_res, h_radii, total_num_peaks=number_of_circles)
    # the hough_cirlce_peaks function takes the imaginary 'hough circle', the anticipated radii, and the anticiapted number of circles
    # it uses this to find the Peak values in 'hough space', the positions of the circles and the radii of the circles

    print("radius is:", radius)
    area = 3.1415926535897984626 * radius * radius
    return area
    print("area is: ", area)
    # Prints the radii of the identified circles

    fig, ax = alt.subplots(ncols=1, nrows=1, figsize=(10, 4))
    image = color.gray2rgb(image)
    for center_y, center_x, radius in zip(
            y, x, radius
    ):  # This for loop draws the circles that were generated earlier
        circy, circx = circle_perimeter(center_y,
                                        center_x,
                                        radius,
                                        shape=image.shape)
        image[circy, circx] = (220, 20, 20)

    ax.imshow(image)  # This loads the edited image into the environment

    alt.show()  # this takes the uploaded image and displays it for the user
Esempio n. 35
0
def generate_circles(im, circle_edges, greens, piece_size, CIRCLE_THRESHOLD,
                     CIRCLE_GREEN_THRESHOLD):
    if im.shape[0] == im.shape[1] == 1:
        return []
    # Find circles (othello pieces)
    print("Circle detection... ", end="", flush=True)
    radii_lim = np.arange(piece_size * 0.8, piece_size * 1.2)
    hough_res = hough_circle(circle_edges, radii_lim)
    prob, cx, cy, radii = hough_circle_peaks(hough_res,
                                             radii_lim,
                                             min_xdistance=int(piece_size),
                                             min_ydistance=int(piece_size),
                                             threshold=CIRCLE_THRESHOLD)

    circles = list(zip(prob, cx, cy, radii))

    circles_not_intersecting = []
    for i, circle in enumerate(circles):
        prob, x, y, rad = circle
        intersecting = False
        for (_, x_, y_, rad_) in circles[:i]:
            dist_sqrd = (x - x_)**2 + (y - y_)**2
            if dist_sqrd < ((rad + rad_) / 2)**2:
                intersecting = True
                break

        if not intersecting:
            circles_not_intersecting.append(circle)

    circles_with_colors = []
    for prob, x, y, rad in circles_not_intersecting:
        rad = int(rad)

        brightness_in_rad = []
        green_in_rad = []

        for x_ in range(-rad, rad):
            for y_ in range(-rad, rad):
                if (x_**2 + y_**2) < (rad - 3)**2:
                    if 0 <= y + y_ < im.shape[0] and \
                       0 <= x + x_ < im.shape[1]:
                        brightness_in_rad.append(im[y + y_, x + x_].sum() / 3)

                        green_in_rad.append(greens[y + y_, x + x_])

        brightness_in_rad = np.array(brightness_in_rad)
        avg_green = sum(green_in_rad) / (len(green_in_rad) + 1)

        blacks = (brightness_in_rad < 0.6).sum()
        whites = (brightness_in_rad > 0.6).sum()

        if avg_green < CIRCLE_GREEN_THRESHOLD:
            circles_with_colors.append((prob, x, y, rad, blacks > whites / 2))

    circles = circles_with_colors

    print("Done")

    return circles
def add_auto_masks_area(areaFile,addMasks=False):
    from skimage.morphology import binary_dilation, binary_erosion, disk
    from skimage import exposure
    from skimage.transform import hough_circle
    from skimage.morphology import convex_hull_image
    from skimage.feature import canny
    from skimage.draw import circle_perimeter

    import h5py


    MASKs = np.zeros(areaFile.attrs['ROI_patches'].shape)
    if 'ROI_masks' in (areaFile.attrs.iterkeys()):
        print 'Masks have already been created'
        awns = raw_input('Would you like to redo them from scratch: (answer y/n): ')
    else:
        awns = 'y'

    if awns=='y':
        MASKs = np.zeros(areaFile.attrs['ROI_patches'].shape)
        for i in range(areaFile.attrs['ROI_patches'].shape[2]):
            patch = areaFile.attrs['ROI_patches'][:,:,i]
            
            tt0 = exposure.equalize_hist(patch)
            tt = 255*tt0/np.max(tt0)
            thresh = 1*tt>0.3*255
            thresh2 = 1*tt<0.1*255

            tt[thresh] = 255
            tt[thresh2] = 0



            edges = canny(tt, sigma=2, low_threshold=20, high_threshold=30)
            try_radii = np.arange(3,5)
            res = hough_circle(edges, try_radii)
            ridx, r, c = np.unravel_index(np.argmax(res), res.shape)
            
            r, c, try_radii[ridx]
            image = np.zeros([20,20,4])
            cx, cy = circle_perimeter(c, r, try_radii[ridx]+2)
            
            try:
                image[cy, cx] = (220, 80, 20, 1)
                original_image = np.copy(image[:,:,3])
                chull = convex_hull_image(original_image)
                image[chull,:] = (255, 0, 0, .4)
                
            except:
                pass
            
            
            MASKs[:,:,i] = (1*image[:,:,-1]>0)
        if addMasks:
            areaFile.attrs['ROI_masks'] = MASKs
    else:
        pass    

    return np.array(MASKs)
Esempio n. 37
0
def find_the_ball(nome):        
    pasta = 'processing/img_recortadas/'
    im = io.imread(pasta + nome)
    
    im2 = im.copy()
    noisy_image = img_as_ubyte(im2[:,:,0])
    noise = np.random.random(noisy_image.shape)
    noisy_image[noise > 0.99] = 255
    noisy_image[noise < 0.01] = 0
    im[:,:,0] = median(noisy_image, disk(1))
    
    noisy_image = img_as_ubyte(im2[:,:,1])
    noise = np.random.random(noisy_image.shape)
    noisy_image[noise > 0.99] = 255
    noisy_image[noise < 0.01] = 0
    im[:,:,1] = median(noisy_image, disk(1))
    
    
    noisy_image = img_as_ubyte(im2[:,:,2])
    noise = np.random.random(noisy_image.shape)
    noisy_image[noise > 0.99] = 255
    noisy_image[noise < 0.01] = 0
    im[:,:,2] = median(noisy_image, disk(1))

    # Load picture and detect edges
    image = img_as_ubyte(im[:,:,0])
    edges = canny(image, sigma=3, low_threshold=30, high_threshold=85)
    
    # Detect two radii
    hough_radii = np.arange(3, 15, 1)
    hough_res = hough_circle(edges, hough_radii)
    
    # Select the most prominent 3 circles
    accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii,
                                               total_num_peaks=3)
    #mean = np.mean(im[cy[:],cx[:],], axis=1)
    # Draw them
    
    
    #_id  = ball(mean, accums)
    #if(_id != -1):
    #accums, center_x, center_y, radius = accums[_id], cx[_id], cy[_id], radii[_id]
    for center_y, center_x, radius, ac in zip(cy, cx, radii, accums):
        #accums, center_x, center_y, radius = accums[0], cx[0], cy[0], radii[0]
        image = color.gray2rgb(image)
        circy, circx = circle(center_y, center_x, radius,
                                        shape=image.shape)
        #image[circy, circx] = 255
        image = im
        if(image[circy, circx, :].mean() > 160 and image[circy, circx, :].mean() < 180 and ac > 0.55 and np.std(image[circy, circx, :]) > 20 and np.std(image[circy, circx, :]) < 45 ):
            print(nome +' - accums: ' +str(round(ac,2)) + ' - mean: '+ str(round(image[circy, circx, :].mean(),2)))
            image[circy, circx] = 255
            io.imsave('img_ball/'+nome, (image).astype('uint8'))
            #plt.imshow(image, cmap=plt.cm.gray)
            #plt.show()
            circy, circx = circle_perimeter(center_y, center_x, radius,
                                        shape=image.shape)
            return center_y, center_x
    return -1,-1
def get_edges(np_image):
    # Get the coordinates of the circle edges
    X = []
    Y = []
    Z = []
    
    circles = []  # to get the outlines of the circles
    C = []  # to get the centres of the circles, in relation to the different areas
    R = []  # to get radii
    
    coords = np.column_stack(np.nonzero(np_image))
    X = np.array(coords[:, 0])
    Y = np.array(coords[:, 1])

    # Fit a circle and compare measured circle area with
    # area from the amount of pixels to remove trash
    XC, YC, RAD, RESID = leastsq_circle(X, Y)

    # Hough radius estimate
    hough_radii = np.arange(RAD - RAD / 2., RAD + RAD / 2.)
    
    # Apply Hough transform
    hough_res = hough_circle(np_image, hough_radii)
         
    centers = []
    accums = []
    radii = []
    
    img = np.zeros_like(np_image)
    
    # For each radius, extract one circle
    for radius, h in zip(hough_radii, hough_res):
        peaks = peak_local_max(h, num_peaks=2)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius, radius])
         
    for idx in np.argsort(accums)[::-1][:1]:
        center_x, center_y = centers[idx]
        C.append((center_x, center_y))
        radius = radii[idx]
        R.append(radius)
        cx, cy = circle_perimeter(int(round(center_x, 0)),
                                  int(round(center_y, 0)),
                                  int(round(radius, 0)))
        circles.append((cx, cy))
        
    if C:
        for cent in C:
            xc, yc = cent
            np_image[int(xc), int(yc)] = 255
            np_image[int(xc)-5:int(xc)+5, int(yc)-5:int(yc)+5] = 255
    
    if circles:
        for per in circles:
            e1, e2 = per
            np_image[e1, e2] = 255
    
    return [C, R, circles, []], np_image
Esempio n. 39
0
def find_well_border(image, segmethod='bimodal', detmethod='region'):
    """
    finds the border of the well to motivate future cropping around spots
        hough_radii are potential radii of the well in pixels
            this should be motivated based on magnification
        edge filter
        fit hough circle
        find the peak of the SINGULAR hough circle

    :param image: np.ndarray
        raw image, not inverted
    :param segmethod: str
        'otsu' or 'hough'
    :return: center x, center y, radius of the one hough circle
    """
    well_mask = thresh_and_binarize(image, method=segmethod, invert=False)
    # Now remove small objects.
    str_elem_size = 10
    str_elem = disk(str_elem_size)
    well_mask = binary_opening(well_mask, str_elem)
    # well_mask = binary_fill_holes(well_mask)

    if detmethod == 'region':
        labels = measure.label(well_mask)
        props = measure.regionprops(labels)

        # let's assume ONE circle for now (take only props[0])
        props = select_props(props,
                             attribute="area",
                             condition="greater_than",
                             condition_value=10**5)
        props = select_props(props,
                             attribute="eccentricity",
                             condition="less_than",
                             condition_value=0.5)
        well_mask[labels != props[0].label] = 0
        cy, cx = props[
            0].centroid  # notice that the coordinate order is different from hough.
        radii = int((props[0].minor_axis_length + props[0].major_axis_length) /
                    4 / np.sqrt(2))
        # Otsu threshold fails occasionally and leads to asymmetric region. Averaging both axes makes the segmentation robust.
        # If above files, try bounding box.

    elif detmethod == 'hough':
        hough_radii = [300, 400, 500, 600]

        well_mask = thresh_and_binarize(image, method='bimodal')

        edges = canny(well_mask, sigma=3)
        hough_res = hough_circle(edges, hough_radii)
        aaccums, cx, cy, radii = hough_circle_peaks(hough_res,
                                                    hough_radii,
                                                    total_num_peaks=1)
        cx, cy = cx[0], cy[0]
        radii = radii[0]
    else:
        cx, cy, radii = None, None, None

    return [cy, cx], radii, well_mask
Esempio n. 40
0
def _detect_spots_hough_circle(image, radius):
	edges = canny(image)
	imshow(edges)
	show()
	hough_radii = np.arange(radius/2, radius*2, 10)
	hough_circles = hough_circle(edges, hough_radii)
	
	print(hough_circles)
Esempio n. 41
0
def count_dishes(out, sink):
    edges = canny(
        sink,
        sigma=2,
        #low_threshold=10,
        high_threshold=0.3
    )
    
    hough_radii = np.arange(25, 70, 1)
    hough_res = hough_circle(edges, hough_radii)
    centers = []
    accums = []
    radii = []

    for radius, h in zip(hough_radii, hough_res):
        num_peaks = 2
        peaks = peak_local_max(h, num_peaks=num_peaks)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * num_peaks)

    sink = color.gray2rgb(sink)
    hits = {}

    for idx in np.argsort(accums)[::-1][:25]:
        center_x, center_y = centers[idx]
        radius = radii[idx]

        if is_sink_hole(center_x, center_y, radius):
            continue

        for d in hits.keys():
            dx, dy, dr = d

            dt = distance(center_x, dx, center_y, dy)
            
            if dt <= 40 and abs(dr - radius) < 50:
                hits[d] += 1
                break
        else:
            hits[(center_x, center_y, radius)] = 1


    dishes = [k for k,v in hits.iteritems()]

    for dish in dishes:
        center_x, center_y, radius = dish

        cx, cy = circle_perimeter(center_y, center_x, radius)

        try:
            sink[cy, cx] = (220, 250, 20)
        except IndexError:
            continue


    draw_res(out, sink, edges)
    return len(dishes)
Esempio n. 42
0
def __tutorial_hough_circle_detection_skiimage(img_path, min_dim=40, max_dim=60):
    """
    This algorithm is crap, the one using opencv is much much better
    :param img_path:
    :param min_dim:
    :param max_dim:
    :return:
    """

    # load picture and detect edges
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
    img_edges = canny(img, sigma=3, low_threshold=10, high_threshold=50)

    centers = []
    accums = []
    radii = []

    # detect all radii within the range
    min_radius = int(min_dim / 2)
    max_radius = int(max_dim / 2)
    hough_radii = np.arange(start=min_radius, stop=max_radius, step=1)
    hough_res = hough_circle(img_edges, hough_radii)

    for radius, h in zip(hough_radii, hough_res):
        # for each radius, extract 2 circles
        num_peaks = 2
        peaks = peak_local_max(h, num_peaks=num_peaks)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * num_peaks)

    img_width = img.shape[1]
    img_height = img.shape[0]

    # get the sorted accumulated values
    # accums_sorted = np.asarray(accums)
    # accums_sorted = accums_sorted[idx_sorted]

    # don't consider circles with accum value less than the threshold
    accum_threshold = 0.3
    idx_sorted = np.argsort(accums)[::-1]

    # draw the most prominent n circles, i.e those
    # with the highest n peaks
    img_color = color.gray2rgb(img)
    for idx in idx_sorted:
        if accums[idx] < accum_threshold:
            continue
        center_y, center_x = centers[idx]
        radius = radii[idx]
        cx, cy = circle_perimeter(center_x, center_y, radius)
        cx[cx > img_width - 1] = img_width - 1
        cy[cy > img_height - 1] = img_height - 1
        img_color[cy, cx] = (220, 20, 20)

    # save the result
    skimage.io.imsave("D://_Dataset//GTSDB//Test_Regions//_img2_.png", img_color)
Esempio n. 43
0
def punchhole_removal(im):
    import numpy as np
    from PIL import Image
    from skimage import io
    from skimage.color import rgba2rgb, rgb2gray
    from skimage.transform import hough_circle, hough_circle_peaks
    from skimage.feature import canny
    from skimage.draw import circle
    from skimage.util import img_as_ubyte

    ''' check for punch holes and remove  '''
    
    max_peaks =  24 #maximum number of peaks to be found. changed from 99 to 24 for reducing the unnecessary punch holes being filled.

    img = np.array(im)# Load picture .
    img_rgb = rgba2rgb(img)# convert to RGB
    img_gray = rgb2gray(img_rgb)# convert to gray
    image = img_as_ubyte(img_gray)
    width, height = image.shape
    x1 =  punchhole_margin
    x2 =  (int)(width - punchhole_margin)
    y1 =  (int)(height - punchhole_margin)
    y2 =  punchhole_margin

    edges = canny(image, 3, 10, 40) # perform canny to detect the edges
    hough_radii = np.arange(31, 34, 1) #get the radius range with step as 1.
    hough_res = hough_circle(edges, hough_radii) # detect the circles centres coordinates

    # Select the most prominent circles based on the max_peaks
    accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii,total_num_peaks=max_peaks)

    for center_y, center_x, radius in zip(cy, cx, radii):

        #if the circles centres fall in the border regions, 
        #get the dominant color near the hole and fill the hole with a linear gradient of the dominant color
        if(((0 < center_y < width) and (0 < center_x < y2)) or \
           ((0 < center_y < width) and (y1 < center_x < height)) or\
           ((0 < center_y < x1) and (0 < center_x < height)) or \
           ((x2 < center_y < width) and (0 < center_x < height))):

            index=0
            rr, cc= circle(center_y, center_x, radius+1, img.shape)
            dominantpix = dominantcolor(center_x, center_y, radius, img)           
            dark_grad = [dominantpix[0], dominantpix[1],dominantpix[2]]
            light_grad = [dominantpix[0]+1, dominantpix[1]+1, dominantpix[2]+1]
            #white_grad = [255,255,255]
            RGBA_list = lineargradient(dark_grad,light_grad,len(list(rr)))   
          
            for i , j in zip(list(rr), list(cc)):
                pixlist = RGBA_list[index]
                pixtuple = tuple(pixlist)
                img[i,j]= (pixtuple[0], pixtuple[1], pixtuple[2], 255)
                index += 1
           
    finalimage=Image.fromarray(img)

    return finalimage
Esempio n. 44
0
def find_boundary(img, min_radius, max_radius):
    edges = canny(img, sigma=0.)
    radii = np.arange(min_radius, max_radius)
    h = hough_circle(edges, radii)
    h_max = np.max(h, axis=(1, 2))
    k = np.min(np.argsort(h_max)[-2:])
    radius = radii[k]
    h = h[k, ...]
    row, col = np.unravel_index(np.argmax(h), h.shape)
    return row, col, radius
Esempio n. 45
0
    def find_circle(self, image, frame, dim, **kw):
        dx, dy = None, None

        pframe = self._preprocess(frame, blur=0)
        edges = canny(pframe, sigma=3)
        hough_radii = arange(dim * 0.9, dim * 1.1, 2)

        hough_res = hough_circle(edges, hough_radii)

        centers = []
        accums = []
        radii = []
        for radius, h in zip(hough_radii, hough_res):
            # For each radius, extract two circles
            num_peaks = 2
            peaks = peak_local_max(h, num_peaks=num_peaks)
            centers.extend(peaks)
            accums.extend(h[peaks[:, 0], peaks[:, 1]])
            radii.extend([radius] * num_peaks)

        # for idx in argsort(accums)[::-1][:1]:
        try:
            idx = argsort(accums)[::-1][0]
        except IndexError:
            return dx, dy

        center_y, center_x = centers[idx]
        radius = radii[idx]

        draw_circle_perimeter(frame, center_x, center_y, radius, (220, 20, 20))
        # cx, cy = circle_perimeter(int(center_x), int(center_y), int(radius))

        # draw perimeter
        # try:
        #     frame[cy, cx] = (220, 20, 20)
        # except IndexError:
        #     pass

        # draw center
        # cx, cy = circle(int(center_x), int(center_y), int(2))
        # frame[cy, cx] = (220, 20, 20)
        draw_circle(frame, center_x, center_y, 2, (220, 20, 20))

        h, w = frame.shape[:2]

        ox, oy = w / 2, h / 2
        dx = center_x - ox
        dy = center_y - oy

        cx, cy = circle(int(ox), int(oy), int(2))
        frame[cy, cx] = (20, 220, 20)

        image.set_frame(frame)
        return float(dx), -float(dy)
Esempio n. 46
0
def find_circles(image, min_r=30, max_r=300, cutoff=0.5, step=4, blur_sigma=3):
    rs = arange(min_r, max_r, step)
    threshold_image = threshold(image)
    hough_space = hough_circle(threshold(image), rs)
    sigma_3d = (blur_sigma,
                blur_sigma,
                float(blur_sigma) / step)
    blurred_hough_space = gaussian_filter(hough_space, sigma=sigma_3d)
    local_maxima = peak_local_max(blurred_hough_space, exclude_border=False)
    circles = column_stack((local_maxima, hough_space[tuple(local_maxima.T)]))
    circles[:,0] = rs[list(circles[:,0])]
    return circles[circles[:,3] > cutoff]
def test_hough_circle():
    # Prepare picture
    img = np.zeros((120, 100), dtype=int)
    radius = 20
    x_0, y_0 = (99, 50)
    x, y = circle_perimeter(y_0, x_0, radius)
    img[y, x] = 1

    out = tf.hough_circle(img, np.array([radius]))

    x, y = np.where(out[0] == out[0].max())
    # Offset for x_0, y_0
    assert_equal(x[0], x_0 + radius)
    assert_equal(y[0], y_0 + radius)
Esempio n. 48
0
def extract_hough_circle(img_rgb, img_gray, out_filepath):
    # Canny
    img = img_as_ubyte(img_gray)
    edges = canny(img, sigma=3, low_threshold=10, high_threshold=50)

    # fig, ax = plt.subplots(nrows=1, ncols=1)
    # ax.imshow(edges, cmap=plt.cm.gray)
    # ax.axis('off')    
    # ax.set_title('Canny Edges for Hough Circle', fontsize=18)
    # plt.tight_layout()
    # plt.savefig('canny_edges_for_hough_circle.png')

    # Detect
    min_radii = 15; max_radii = 30; step_radii = 1
    plausible_radii = np.arange(min_radii, max_radii, step_radii)

    hough_circles = hough_circle(edges, plausible_radii)

    centers = []; accums = []; radii = []
    for radius, h in zip(plausible_radii, hough_circles):
        n_extracted_circle = 1 # ...for each radius
        peaks = peak_local_max(h, num_peaks=n_extracted_circle)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * n_extracted_circle)

    # Draw the most prominent circles
    n_top_circle = 15
    fig, ax = plt.subplots(ncols=1, nrows=1)
    for idx in np.argsort(accums)[::-1][:n_top_circle]:
        center_x, center_y = centers[idx]
        center_color = (0, 225, 0)
        img_rgb[center_x, center_y] = center_color

        radius = radii[idx]
        perim_color = (255, 0, 0)
        perim_x_list, perim_y_list = circle_perimeter(center_y, center_x, radius)
        # if all(i < img_rgb.shape[1] for i in perim_x_list) and all(i < img_rgb.shape[0] for i in perim_y_list):
        #     img_rgb[perim_y_list, perim_x_list] = perim_color
        for perim_x, perim_y in zip(perim_x_list, perim_y_list):
            if perim_x < img_rgb.shape[1] and perim_y < img_rgb.shape[0]:
                img_rgb[perim_y, perim_x] = perim_color

    ax.imshow(img_rgb, cmap=plt.cm.gray)
    ax.axis('off')
    ax.set_title('Hough Circle', fontsize=18)
    plt.tight_layout()
    plt.savefig(out_filepath)
    plt.close(fig)
def test_hough_circle_extended():
    # Prepare picture
    # The circle center is outside the image
    img = np.zeros((100, 100), dtype=int)
    radius = 20
    x_0, y_0 = (-5, 50)
    y, x = circle_perimeter(y_0, x_0, radius)
    img[x[np.where(x > 0)], y[np.where(x > 0)]] = 1

    out = tf.hough_circle(img, np.array([radius], dtype=np.intp), full_output=True)

    x, y = np.where(out[0] == out[0].max())
    # Offset for x_0, y_0
    assert_equal(x[0], x_0 + radius)
    assert_equal(y[0], y_0 + radius)
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]
Esempio n. 51
0
def findNodesHoughCircles(cannyEdges, hough_radii):
    hough_res = hough_circle(cannyEdges, hough_radii)
    
    centers = []
    accums = []
    radii = []

    #print hough_res
    for radius, h in zip(hough_radii, hough_res):
        peaks = peak_local_max(h)
        #print peaks
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * len(peaks))

    #Sort each list by accums
    #We swap the centers, since they are ordered as y, x
    tupleCenters = [(center[1], center[0]) for center in centers]
    accums, radii, centers = zip(*sorted(zip(accums, radii, tupleCenters))[::-1])
    
    disjointCenters = []
    disjointRadii = []
    disjointAccums = []
    
    removed = [False for i in xrange(len(centers))]
    #Loop through the circles in order of their weight
    minRadiusDist = getMinNodeDist()
    for i in xrange(len(centers)):
        #print "Next index: ", i
        if(not removed[i]):
            #If our current circle does not overlap with previous circles, add it.
            #Then remove all later overlapping circles
            center_y, center_x = centers[i]
            disjointCenters.append(centers[i])
            disjointRadii.append(radii[i])
            disjointAccums.append(accums[i])
            
            for j in xrange(i + 1, len(centers)):
                newCenter_y, newCenter_x = centers[j]
                newRadius = radii[i]
                distSq = findDistSqPoints(center_x, center_y, newCenter_x, newCenter_y)
                neededDist = radius + newRadius + minRadiusDist
                if(distSq < neededDist*neededDist):
                    removed[j] = True
    
    print "Disjoint centers: ", disjointCenters
    print "Disjoint accums: ", disjointAccums
    return disjointAccums, disjointCenters, disjointRadii
def fit_central_circle(image, radius_lower_bound=170, radius_upper_bound=190):
    """Find the centre and radius of the central circle in image. Analysis is
    restrictied the given bounds for the radius of the circle."""

    smoothed = smooth_gaussian(image.astype(np.float), sigma=5)
    edges = find_edges_sobel(smoothed)
    thresh = threshold_otsu(edges)

    hmm = 170, 190
    hough_radii = np.arange(140, 170, 2)
    hough_res = hough_circle(thresh, hough_radii)

    circles = find_n_best_hough_circles(hough_radii, hough_res, 1)
    circle = circles[0]

    return circle
Esempio n. 53
0
def find_center(saas_image, sigma=0.8, num_circles=5):
    """
    Find the center of the image

    :param saas_image: A SAAS image object.
    :param sigma: The amount of gaussian blurring
    :param num_circles: The number of circles to find.

    Returns:

    """
    edges = filter.canny(saas_image.roi_data, sigma=sigma)
    hough_radii = np.arange(10, 70, 1)
    hough_res = hough_circle(edges, hough_radii)
    centers = []
    accums = []
    radii = []
    for radius, h in zip(hough_radii, hough_res):
        # For each radius, extract two circles
        peaks = peak_local_max(h, num_peaks=2)
        if peaks != []:
            centers.extend(peaks)
            accums.extend(h[peaks[:, 0], peaks[:, 1]])
            radii.extend([radius, radius])

    best_centers = []
    best_radii = []
    best_x = []
    best_y = []
    number_of_best_circles = num_circles
    for idx in np.argsort(accums)[::-1][:number_of_best_circles]:
        center_x, center_y = centers[idx]
        best_x.append(center_x)
        best_y.append(center_y)
        best_centers.append(centers[idx])
        best_radii.append(radii[idx])

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 6))
    ax1.imshow(edges)
    ax2.imshow(self.roi_data, cmap=cm.gray)
    for center, radius in zip(best_centers, best_radii):
        circle = plt.Circle((center[1], center[0]), radius, color='r', fill=False)
        ax2.add_patch(circle)
    print("Calibrated Center X = %s +/- %s" % (np.average(best_x), np.std(best_x)))
    print("Calibrated Center Y = %s +/- %s" % (np.average(best_y), np.std(best_y)))
    return np.array([[np.average(best_x), np.std(best_x)],
                     [np.average(best_y), np.std(best_y)]])
def find_circles(image, input_radii):
    result = hough_circle(image, input_radii)
    centers = []
    accums = []
    radii = []
    for radius, h in zip(input_radii, result):
        # For each radius, extract two circles
        peaks = peak_local_max(h, num_peaks=2)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius, radius])
    circles = []
    for idx in np.argsort(accums)[::-1][:5]:
        center_x, center_y = centers[idx]
        radius = radii[idx]
        circles.append((center_x, center_y, radius))
    return circles
def test_hough_circle_peaks_total_peak():
    img = np.zeros((120, 100), dtype=int)

    x_0, y_0, rad_0 = (99, 50, 20)
    y, x = circle_perimeter(y_0, x_0, rad_0)
    img[x, y] = 1

    x_1, y_1, rad_1 = (49, 60, 30)
    y, x = circle_perimeter(y_1, x_1, rad_1)
    img[x, y] = 1

    radii = [rad_0, rad_1]
    hspaces = tf.hough_circle(img, radii)
    out = tf.hough_circle_peaks(hspaces, radii, min_xdistance=1, min_ydistance=1,
                                threshold=None, num_peaks=np.inf, total_num_peaks=1)
    assert_equal(out[1][0], np.array([y_1,]))
    assert_equal(out[2][0], np.array([x_1,]))
    assert_equal(out[3][0], np.array([rad_1,]))
Esempio n. 56
0
    def centers_radii(cls, img):
        centers = []
        accums = []
        radii = []

        edges = canny(img, sigma=3.0)
        # Detect two radii
        hough_radii = np.arange(15, 30, 2)
        hough_res = hough_circle(edges, hough_radii)
        for radius, h in zip(hough_radii, hough_res):
            # For each radius, extract two circles
            num_peaks = 2
            peaks = peak_local_max(h, num_peaks=num_peaks)
            centers.extend(peaks)
            accums.extend(h[peaks[:, 0], peaks[:, 1]])
            radii.extend([radius] * num_peaks)

        return centers, radii, edges
Esempio n. 57
0
def getCircles(image, radius):
    # use the circular Hough transform to find the circles
    cimg = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
    cimg = cv.GaussianBlur(cimg, (5, 5), 0)
    circles = []
    # apply an edge filter first
    canimg = filter.canny(img_as_ubyte(img), sigma=1, low_threshold=120,
                    high_threshold=126)
    hough_radii = np.array([radius])
    hough_res = hough_circle(canimg, hough_radii)
    centers =[]; accums =[]; radii =[]
    numcircles = 9
    for r, h in zip(hough_radii, hough_res):
        peaks = peak_local_max(h, num_peaks = numcircles, min_distance=50, threshold_rel=0.15)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend ([r]* numcircles )
    for i in np.argsort(accums)[::-1][:numcircles]:
        circles.append([centers[i][1], centers[i][0], radii[i]])
    return circles
Esempio n. 58
0
def extract_hough(img_gray):
    img = img_as_ubyte(img_gray)
    edges = canny(img, sigma=5, low_threshold=10, high_threshold=50)

    fig, ax = plt.subplots(nrows=1, ncols=1)
    ax.imshow(edges, cmap=plt.cm.gray)
    ax.axis('off')
    ax.set_title('Canny filter', fontsize=20)
    plt.savefig('canny_edges.png')

    # Detect two radii
    hough_radii = np.arange(15, 30, 2)
    hough_res = hough_circle(edges, hough_radii)
    print len(hough_res)

    centers = []
    accums = []
    radii = []

    for radius, h in zip(hough_radii, hough_res):
        # For each radius, extract two circles
        num_peaks = 2
        peaks = peak_local_max(h, num_peaks=num_peaks)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * num_peaks)

    # Draw the most prominent 15 circles
    fig, ax = plt.subplots(ncols=1, nrows=1)
    img_rgb = color.gray2rgb(img)
    for idx in np.argsort(accums)[::-1][:15]:
        center_x, center_y = centers[idx]
        radius = radii[idx]
        cx, cy = circle_perimeter(center_y, center_x, radius)
        img_rgb[cy, cx] = (220, 20, 20)

    ax.imshow(img_rgb, cmap=plt.cm.gray)
    ax.axis('off')
    ax.set_title('Hough Circle', fontsize=20)
    plt.tight_layout()
    plt.savefig('hough.png')