示例#1
0
def test_circle_perimeter_andres():
    img = np.zeros((15, 15), 'uint8')
    rr, cc = circle_perimeter(7, 7, 0, method='andres')
    img[rr, cc] = 1
    assert(np.sum(img) == 1)
    assert(img[7][7] == 1)

    img = np.zeros((17, 15), 'uint8')
    rr, cc = circle_perimeter(7, 7, 7, method='andres')
    img[rr, cc] = 1
    img_ = np.array(
        [[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
         [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
         [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
         [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
         [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
         [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
         [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
         [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
         [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
         [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
         [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
         [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
         [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
         [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
         [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
    )
    assert_array_equal(img, img_)
示例#2
0
def test_circle_perimeter_andres():
    img = np.zeros((15, 15), "uint8")
    rr, cc = circle_perimeter(7, 7, 0, method="andres")
    img[rr, cc] = 1
    assert np.sum(img) == 1
    assert img[7][7] == 1

    img = np.zeros((17, 15), "uint8")
    rr, cc = circle_perimeter(7, 7, 7, method="andres")
    img[rr, cc] = 1
    img_ = np.array(
        [
            [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
            [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
            [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
            [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
            [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        ]
    )
    assert_array_equal(img, img_)
示例#3
0
def test_circle_perimeter_bresenham_shape():
    img = np.zeros((15, 20), 'uint8')
    rr, cc = circle_perimeter(7, 10, 9, method='bresenham', shape=(15, 20))
    img[rr, cc] = 1
    shift = 5
    img_ = np.zeros((15 + 2 * shift, 20), 'uint8')
    rr, cc = circle_perimeter(7 + shift, 10, 9, method='bresenham', shape=None)
    img_[rr, cc] = 1
    assert_array_equal(img, img_[shift:-shift, :])
def show_matching(img, img2, matching):
    print "matching..."
    ip_match = build_match_dic(img, img2, matching)

    print "Constructing intermediate image..."
    padding = 5 #padding around the edges

    bar = np.ndarray((img.shape[0], 5))
    bar.fill(1.0)
    viewer = ImageViewer(img)
    viewer.show()
    img3 = np.column_stack((img, bar, img2))
    viewer = ImageViewer(img3)
    viewer.show()

    img3 = img_as_ubyte(img3)

    viewer = ImageViewer(img3)
    viewer.show()

    img3 = np.pad(img3, pad_width=padding, mode='constant', constant_values=(0))


    viewer = ImageViewer(img3)
    viewer.show()
    print "Drawing lines..."

    colimg = color.gray2rgb(img3)
    for k,v in random.sample(ip_match.items(), int(float(len(ip_match.keys()))*0.005)):
        #Choose a random colour:
        col = [random.randint(0,255),random.randint(0,255),random.randint(0,255)]

        #Calculate coordinates after padding:
        x1 = k[0]+padding
        y1 = k[1]+padding
        x2 = v[0]+padding
        y2 = v[1] + img.shape[1]+bar.shape[1]+padding

        #Draw the points in both images:
        rr, cc = circle_perimeter(x1, y1, 3)
        colimg[rr, cc] = col
        rr, cc = circle_perimeter(x2, y2, 3)
        colimg[rr, cc] = col

        #Draw a line between the points:
        rr, cc = line(x1,y1,x2,y2)
        colimg[rr, cc] = col

    #Show the result:
    viewer = ImageViewer(colimg)
    viewer.show()
示例#5
0
def circle_markers(blobs, pic_shape):
    '''Return array with circles around foci found'''

    markers_rad = np.zeros(pic_shape, dtype = np.bool)

    x_max, y_max = pic_shape

    for blob in blobs:

        x, y, r = blob

        r = r*2

        rr, cc = circle_perimeter(x, y, np.round(r).astype(int))
        rr_new, cc_new = [], []

        for x_c,y_c in zip(rr,cc):

            if (x_c >= 0) and (x_c < x_max) and (y_c >= 0) and (y_c < y_max):
                rr_new.append(x_c)
                cc_new.append(y_c)

        markers_rad[rr_new, cc_new] = True

    selem = np.array([0,1,0,1,1,1,0,1,0], dtype=bool).reshape((3,3))

    for i in range(4):
        markers_rad = binary_dilation(markers_rad, selem)

    return markers_rad
示例#6
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()
示例#7
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,
示例#8
0
def compute_singularity_measure(gradients):
    """ Compute singularity measure of data
    """
    # precompute closed curve coordinates
    circle_rad = 5

    grad_dim = gradients[0].shape
    closed_curves = np.empty(grad_dim, dtype=(list, list))
    for j in range(grad_dim[1]):
        for i in range(grad_dim[0]):
            rr, cc = circle_perimeter(
                i, j, circle_rad,
                method='andres', shape=grad_dim
            )
            closed_curves[i, j] = (rr, cc)

    # find singularities
    singularities = []
    for grad in gradients:
        width, height = grad.shape

        singularity = np.empty((width, height))
        for j in range(height):
            for i in range(width):
                res = np.sum(grad[closed_curves[i, j]])
                singularity[i, j] = res
        singularity = np.array(singularity)

        singularities.append(singularity)

    return np.array(singularities)
示例#9
0
def gen_ring_mask(votes, img, y0, x0, r0):
    import skimage.draw as draw
    #rad = np.sum(np.sum(votes[:,y0-1:y0+2,x0-1:x0+2], axis=1), axis=1)
    rad = votes[:, y0, x0]
    peaks = np.where(np.r_[False, rad[1:] > rad[:-1]] 
                & np.r_[rad[:-1] > rad[1:], False]
                & (rad >= 0.2*rad.max()))
    peaks = peaks[0]
    coeffs = []
    xx = range(len(rad))
    flag = np.zeros(len(rad), dtype='uint8')

    # fit guassian peak
    for p in peaks:
        if p > 1.3*r0:
            break
        yy = np.copy(rad)
        yy[:p-3] = 0
        yy[p+4:] = 0
        cc = fit_gauss(xx, yy, rad[p], p, 2)
        flag[np.floor(cc[1]-cc[2]):np.ceil(cc[1]+cc[2])+1] = 1
        coeffs.append(cc)
    #print flag, coeffs

    # create image mask
    mask = np.zeros(img.shape, dtype='uint8')
    for _r, _f in enumerate(flag):
        if _f == 1:
             _y, _x = draw.circle_perimeter(y0, x0, _r, 'andres')
             mask[_y, _x] = 1
    return mask
        def onclick(self,event):
            if event.inaxes==ax:
                if event.button==1:
                    if np.sum(MASKs[self.ind])==0:
                        
                        cx, cy = circle_perimeter(int(event.ydata), int(event.xdata), 3)
                        MASKs[self.ind][cx,cy] = (220, 80, 20, 1)
                        original_image = np.copy(MASKs[self.ind][:,:,3])
                        chull = convex_hull_image(original_image)
                        MASKs[self.ind][chull,:] = (255, 0, 0, .4)


                        ax.cla()
                        data =  areaFile.attrs['ROI_patches'][:,:,self.ind]
                        ax.imshow(data,cmap='binary_r')
                        ax.imshow(MASKs[self.ind])

                elif event.button==3:
                    MASKs[self.ind] = np.zeros(MASKs[self.ind].shape)

                    
                    data = areaFile.attrs['ROI_patches'][:,:,self.ind]

                    ax.cla()
                    ax.imshow(data,cmap='binary_r')
                    ax.imshow(MASKs[self.ind])
示例#11
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()
示例#12
0
def draw_keypoints(img, keypoints, draw_prob):
    """Draws for each keypoint a circle (roughly matching the sigma of the scale)
    with a line for the orientation.
    Args:
        img    The image to which to add the keypoints (gets copied)
        keypoints The keypoints to draw
        draw_prob Probability of drawing a keypoint (the lower the less keypoints are drawn)
    Returns:
        Image with keypoints"""
    height, width = img.shape
    img = np.copy(img)

    # convert from grayscale image to RGB so that keypoints can be drawn in red
    img = img[:, :, np.newaxis]
    img = np.repeat(img, 3, axis=2)

    for (y, x), orientation, scale_idx, scale_size, kp_type in keypoints:
        if draw_prob < 1.0 and random.random() <= draw_prob:
            # draw the circle
            radius = int(scale_size)
            rr, cc = draw.circle_perimeter(y, x, radius, shape=img.shape)
            img[rr, cc, 0] = 1.0
            img[rr, cc, 1:] = 0

            # draw orientation
            orientation = util.quantize(orientation, [-135, -90, -45, 0, 45, 90, 135, 180])
            x_start = x
            y_start = y
            if orientation == 0:
                x_end = x + radius
                y_end = y
            elif orientation == 45:
                x_end = x + radius*(1/math.sqrt(2))
                y_end = y + radius*(1/math.sqrt(2))
            elif orientation == 90:
                x_end = x
                y_end = y + radius
            elif orientation == 135:
                x_end = x - radius*(1/math.sqrt(2))
                y_end = y - radius*(1/math.sqrt(2))
            elif orientation == 180:
                x_end = x - radius
                y_end = y
            elif orientation == -135:
                x_end = x - radius*(1/math.sqrt(2))
                y_end = y - radius*(1/math.sqrt(2))
            elif orientation == -90:
                x_end = x
                y_end = y - radius
            elif orientation == -45:
                x_end = x + radius*(1/math.sqrt(2))
                y_end = y - radius*(1/math.sqrt(2))
            x_end = np.clip(x_end, 0, width-1)
            y_end = np.clip(y_end, 0, height-1)
            rr, cc = draw.line(int(y_start), int(x_start), int(y_end), int(x_end))
            img[rr, cc, 0] = 1.0
            img[rr, cc, 1:] = 0
    img = np.clip(img, 0, 1.0)

    return img
def quantify_yeast_growth(input_filename, annotation_filename, 
                            profile_filename):
    

    downscaled = load_and_downscale(input_filename)
    annotation = AnnotatedImage.from_grayscale(downscaled)

    circle = fit_central_circle(downscaled)

    circle_coords = circle_perimeter(*circle)
    annotation[circle_coords] = 0, 255, 0

    x, y, r = circle
    center = (x, y)

    xdim, ydim, = downscaled.shape
    line_length = ydim - y

    mean_profile_line = find_mean_profile_line(downscaled, annotation,
                                center, -math.pi/4, math.pi/4, line_length)


    record_line_profile(profile_filename, mean_profile_line)

    with open(annotation_filename, 'wb') as f:
        f.write(annotation.png())
示例#14
0
	def remove_deep_points(self, CIRCLE_RADIUS = 5, MINIMUM_BOUNDARY = 70):
		for point in self.POINTS_initial:
			segments = []
			circle_x, circle_y = circle_perimeter(point[0],point[1],CIRCLE_RADIUS)
			circle_points = np.array(list(sorted(set(zip(circle_x,circle_y)))))

			sortedpoints = np.empty([len(circle_points), 2], dtype=int)

			test1 = circle_points[circle_points[:,0] == point[0] - CIRCLE_RADIUS]
			start = len(test1)
			end = len_cpoints = len(sortedpoints)
			sortedpoints[0:start] = test1

			for x in xrange(point[0] - CIRCLE_RADIUS + 1, point[0] + CIRCLE_RADIUS):
				test1 = circle_points[circle_points[:,0] == x]
				testlen = len(test1)
				if x <= point[0]:
					sortedpoints[start:start+testlen/2] = test1[testlen/2:]
					sortedpoints[end-testlen/2:end] = test1[:testlen/2]
				else:
					sortedpoints[start:start+testlen/2] = test1[testlen/2:][::-1]
					sortedpoints[end-testlen/2:end] = test1[:testlen/2][::-1]
				start += testlen/2
				end -= testlen/2

			test1 = circle_points[circle_points[:,0] == point[0] + CIRCLE_RADIUS]
			sortedpoints[start:start + len(test1)] = test1[::-1]

			for c_perimeter in sortedpoints:
				segments.append(True)
				line_x, line_y = line(point[0], point[1], c_perimeter[0], c_perimeter[1])
				for line_points in zip(line_x,line_y)[1:]:
					# if original_image[line_points[0]][line_points[1]] != 0:
					if self.FOOTPRINT_cleaned_opening[line_points[0]][line_points[1]] != 0:
						segments[-1] = False
						break

			min_boundpoints = (MINIMUM_BOUNDARY / 360.0) * len_cpoints

			seg_sizes = []
			new_segment = True
			for segment in segments:
				if segment:
					if new_segment:
						seg_sizes.append(1)
						new_segment = False
					else:
						seg_sizes[-1] += 1
				else:
					new_segment = True

			if segments[0] == True and segments[-1] == True and len(seg_sizes) > 1:
				seg_sizes[0] = seg_sizes[0] + seg_sizes[-1]
				seg_sizes.pop()
			
			if(len(seg_sizes) == 0 or max(seg_sizes) < min_boundpoints):
				# boundary_image[point[0]][point[1]] = 0							#TAMA BANG TANGGALIN?

				if (point[0],point[1]) in self.POINTS_ordered:  ## IDENTIFY KUNG BAKIT NAGKA-ERRROR, EXAMPLE pt000120_merged4.py obj 1301
					self.POINTS_ordered.remove((point[0],point[1]))
示例#15
0
def find_iris(image, pupil, **kwargs):
    buffer = 20
    # run canny
    image = filter.canny(image, sigma=1, low_threshold=10, high_threshold=50)
    cx, cy, radius = pupil

    segments = get_segments(400, step=0.01)
    # get ray directions
    directions = zip(map(cos, segments[0]), map(sin, segments[0]))
    shape = image.shape
    points = []
    for d in directions:
        start = (cx + (radius + buffer) * d[0], cy + (radius + buffer)*d[1])
        ray = Ray(image, start, d)
        point = ray.fire()
        if point != None:
            points.append(point)

    for p in points:
        x, y = circle_perimeter(int(p[0]), int(p[1]), 3)
        x = x[x < rgb.shape[0]]
        y = y[y < rgb.shape[1]]
        rgb[x,y] = (220, 40, 40)

    e = Ellipse().fit_with_center(None, points)
    return image, points, e
def form_mask_BR_v2(start_temp, max_temp, temp_rate):
	dtype = [('temp', float), ('mask', np.ndarray), ('dist', np.ndarray)]
	masks = []
	#IMPROVEMENT!!!
	#MINUS LAST COORDINATES TO NEXT TEMPERATURE
	#LESS POINTS TO CHECK
	while (start_temp <= max_temp):
		coordinates = []
		coor_dist = []
		distance = int(round(start_temp))
		array_size = distance * 2 + 1
		img = np.zeros((array_size, array_size), dtype=np.uint8)
		rr, cc = circle_perimeter(distance, distance, distance)
		img[rr, cc] = 1
		rr,cc = np.nonzero(ndimage.binary_fill_holes(img).astype(int))
		img[rr, cc] = 1

		for idx in xrange(0, len(rr)):
			dist_temp = np.linalg.norm(np.array([rr[idx], cc[idx]]) - np.array([distance, distance]))
			if dist_temp <= start_temp:
				coordinates.append([rr[idx], cc[idx]])
				coor_dist.append(dist_temp)

		# coordinates.remove([distance, distance])
		coordinates = coordinates - np.array([distance, distance])
		masks.append((start_temp, coordinates, np.array(coor_dist)))
		start_temp += temp_rate

	return np.array(masks, dtype=dtype)
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)
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
def get_perimeter(img):
    """
    :param img:
    :return:
    """
    cx = img.shape[0]/2
    cc, rr = circle_perimeter(cx - 1, cx - 1, 256)
    return rr, cc
示例#20
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)
示例#21
0
def auto_find_center_rings(avg_img, sigma=1, no_rings=4, min_samples=3,
                           residual_threshold=1, max_trials=1000):
    """This will find the center of the speckle pattern and the radii of the
    most intense rings.

    Parameters
    ----------
    avg_img : 2D array
        shape of the image
    sigma : float, optional
        Standard deviation of the Gaussian filter.
    no_rings : int, optional
        number of rings
    min_sample : int, optional
        The minimum number of data points to fit a model to.
    residual_threshold : float, optional
        Maximum distance for a data point to be classified as an inlier.
    max_trials : int, optional
        Maximum number of iterations for random sample selection.

    Returns
    -------
    center : tuple
        center co-ordinates of the speckle pattern
    image : 2D array
        Indices of pixels that belong to the rings,
        directly index into an array
    radii : list
        values of the radii of the rings

    Note
    ----
    scikit-image ransac
    method(http://www.imagexd.org/tutorial/lessons/1_ransac.html) is used to
    automatically find the center and the most intense rings.
    """

    image = img_as_float(color.rgb2gray(avg_img))
    edges = feature.canny(image, sigma)
    coords = np.column_stack(np.nonzero(edges))
    edge_pts_xy = coords[:, ::-1]
    radii = []

    for i in range(no_rings):
        model_robust, inliers = ransac(edge_pts_xy, CircleModel, min_samples,
                                       residual_threshold,
                                       max_trials=max_trials)
        if i == 0:
            center = int(model_robust.params[0]), int(model_robust.params[1])
        radii.append(model_robust.params[2])

        rr, cc = draw.circle_perimeter(center[1], center[0],
                                       int(model_robust.params[2]),
                                       shape=image.shape)
        image[rr, cc] = i + 1
        edge_pts_xy = edge_pts_xy[~inliers]

    return center, image, radii
示例#22
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)
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,]))
示例#24
0
def mask_transform(f, y0, x0, r, dr):
    import skimage.draw as draw
    _f0 =  np.zeros(f.shape)
    _f1 =  np.zeros(f.shape)
    for _ir in range(r-dr, r+dr+1):
        yy, xx = draw.circle_perimeter(y0, x0, _ir, 'andres')
        _f0[yy, xx] = 1
    _f1[np.where(np.logical_and(f, _f0))] = 1
    _v, _fv = fuzzyHT(_f1, range(10, 50))
    return _f1, _fv
def detect(path,**kwargs):
    d = Dataset('./data')
    image = d.read(path)
    global rgb
    rgb = d.read(path)
    pupil = find_pupil(image, 15)[0]
    e = Ellipse()
    e._axes = (pupil[2], pupil[2])
    e._center = pupil[0:2]
    x, y = circle_perimeter(pupil[0], pupil[1], pupil[2])
    #rgb[x,y] = 255
    return e, image
示例#26
0
文件: piro.py 项目: sy9976/piro_proj1
def get_circle_perimeter(size, y, x, r): #zwraca czarny obraz z wyrysowanym okregiem o zadanych parametrach
  max_y, max_x = size
  w = np.zeros(size)
  rr, cc = circle_perimeter(y, x, r)
  trr = np.array([0])
  tcc = np.array([0])
  for i, r in enumerate(rr):
    if r >= 0 and r < max_y:
      if cc[i] >= 0 and cc[i] < max_x:
        trr = np.concatenate((trr, [r]))
        tcc = np.concatenate((tcc, [cc[i]]))
  w[trr, tcc] = 1
  return w
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

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

    x, y = np.where(out[0] == out[0].max())
    assert_equal(x[0], x_0)
    assert_equal(y[0], y_0)
示例#28
0
def _helper_find_rings(proc_method, center, radii_list):
    x, y = center
    image_size = (256, 265)
    numpy.random.seed(42)
    noise = np.random.rand(*image_size)
    tt = np.zeros(image_size)
    for r in radii_list:
        rr, cc = skd.circle_perimeter(x, y, r)
        tt[rr, cc] = 1
    tt = binary_dilation(tt, structure=np.ones((3, 3))).astype(float) * 100

    tt = tt + noise
    res = proc_method(tt)
    assert_equal(res, center)
示例#29
0
def detect(d, i,**kwargs):
    image = d.read(d.images[i])
    global rgb
    rgb = d.read(d.images[i], flatten=False)
    pupil = find_pupil(image)[0]
    img, points, ellipse = find_iris(image, pupil, **kwargs)
    x, y = circle_perimeter(pupil[0], pupil[1], pupil[2])
    rgb[x,y] = (220, 40, 40)
    ex, ey = ellipse.center
    major, minor = ellipse.axes
    orientation = ellipse.orientation
    x, y = ellipse_perimeter(int(ex), int(ey), int(major), int(minor), orientation)
    rgb[x,y] = (220, 40, 40)
    imshow(rgb)
示例#30
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)
示例#31
0
def test_hessian_matrix_eigvals_3d(im3d, dtype):
    im3d = im3d.astype(dtype, copy=False)
    H = hessian_matrix(im3d)
    E = hessian_matrix_eigvals(H)
    out_dtype = _supported_float_type(dtype)
    assert all(a.dtype == out_dtype for a in E)

    # test descending order:
    e0, e1, e2 = E
    assert np.all(e0 >= e1) and np.all(e1 >= e2)

    E0, E1, E2 = E[:, E.shape[1] // 2]  # cross section
    row_center, col_center = np.array(E0.shape) // 2
    circles = [
        draw.circle_perimeter(row_center, col_center, radius, shape=E0.shape)
        for radius in range(1, E0.shape[1] // 2 - 1)
    ]
    response0 = np.array([np.mean(E0[c]) for c in circles])
    response2 = np.array([np.mean(E2[c]) for c in circles])
    # eigenvalues are negative just inside the sphere, positive just outside
    assert np.argmin(response2) < np.argmax(response0)
    assert np.min(response2) < 0
    assert np.max(response0) > 0
示例#32
0
def test_circle_detect():
    from guang.cv.video import getFrame
    import matplotlib.pyplot as plt
    from skimage.draw import circle_perimeter
    from skimage import color

    # dst = cv2.pyrMeanShiftFiltering(image, 10, 100)   #边缘保留滤波EPF
    fps, size_17, img = getFrame(
        filename=r'C:\Users\beidongjiedeguang\Desktop\实验\62.avi',
        frameNum=723,
    )
    image = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    accums, cx, cy, radii = circle_detect(image,
                                          rangeR=[100, 250],
                                          total_num_peaks=1)
    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)

    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(20, 10))
    ax.imshow(image, cmap=plt.cm.gray)
    plt.show()
示例#33
0
def test_hough_circle_peaks_total_peak_and_min_distance():
    img = np.zeros((120, 120), dtype=int)
    cx = cy = [40, 50, 60, 70, 80]
    radii = range(20, 30, 2)
    for i in range(len(cx)):
        y, x = circle_perimeter(cy[i], cx[i], radii[i])
        img[x, y] = 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=2,
                                       normalize=True)

    # 2nd (4th) circle is removed as it is close to 1st (3rd) oneself.
    # 5th is removed as total_num_peaks = 2
    assert_equal(out[1], np.array(cy[:4:2]))
    assert_equal(out[2], np.array(cx[:4:2]))
    assert_equal(out[3], np.array(radii[:4:2]))
示例#34
0
def do(frame):
    # rf = cv2.cvtColor(rf, cv2.COLOR_BGR2GRAY)
    lex, rex, ley, hey = calc_bounds(frame)

    rr, cc = draw.circle_perimeter(lex + 150, ley + 150, 150)
    frame[rr, cc, 0] = (255, 0, 0)
    # frame = frame[ley:hey, lex:rex, :]
    for_net = cv2.resize(frame, (150, 150))
    for_net = np.swapaxes(for_net, 0, 2)
    for_net = for_net.reshape(
        (1, 3, 150, 150) +
        for_net.shape)  # this is a Numpy array with shape (1, 3, 150, 150)

    res = model.predict(for_net)
    print(res)

    pass
    # res = net1.predict(rf.reshape(1,9216) / 255)[0]
    # res = net1.predict(rf.reshape(1,1,96,96) / 255)[0]
    # for x,y in zip(res[0::2]*48+48, res[1::2]*48+48):
    #     cv2.drawMarker(rf, (int(x), int(y)), 255)

    return frame
示例#35
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
def main():
    img = os.path.join(os.getcwd(), 'newstage1.jpg')
    image = imread(img, as_gray=True)
    image = img_as_ubyte(image)
    image = ndi.gaussian_filter(image, 1)

    edges1 = canny(image, sigma=1, low_threshold=10, high_threshold=50)

    hough_radii = np.arange(20, 60, 3)
    hough_res = hough_circle(edges1, hough_radii)

    accums, cx, cy, radii = hough_circle_peaks(hough_res,
                                               hough_radii,
                                               total_num_peaks=3)

    print(len(radii))

    image = color.gray2rgb(image)

    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] = (220, 20, 20)

    fig, (ax1, ax2) = plt.subplots(nrows=1,
                                   ncols=2,
                                   figsize=(10, 4),
                                   sharex=True,
                                   sharey=True)

    ax1.imshow(image, cmap=plt.cm.gray)

    ax2.imshow(edges1, cmap=plt.cm.gray)
    plt.show()
示例#37
0
def hough_circles(edge_map, radius_range):
    # you can compare you solution, to a reference implementation:
    #acc = hough_circle(edge_map, radius_range) # <- remove this
    angles = np.arange(0, (2. - 2. / 360) * np.pi, 1. / 360)

    print(edge_map.shape)

    acc = np.zeros((radius_range.shape[0], edge_map.shape[0],
                    edge_map.shape[1])).astype(np.float32)

    for i, radius in enumerate(radius_range):
        print(i)
        with np.nditer(edge_map, flags=['multi_index']) as it:
            for px in it:
                if px > 0:
                    rr, cc = draw.circle_perimeter(it.multi_index[1],
                                                   it.multi_index[0], radius)
                    rr_FilterIndex = np.where((rr >= edge_map.shape[1])
                                              | (rr < 0))
                    cc_FilterIndex = np.where((cc >= edge_map.shape[0])
                                              | (cc < 0))
                    val_FilterIndex = np.append(rr_FilterIndex, cc_FilterIndex)
                    rr = np.delete(rr, val_FilterIndex)
                    cc = np.delete(cc, val_FilterIndex)

                    #print(rr, cc)

                    acc[i, cc, rr] += 1

                    #skimage.draw
                    #acc[i] += (radius * np.cos(angles) + it.multi_index[0], radius * np.sin(angles) + it.multi_index[1])
        print(acc[i])
    acc /= acc.max()

    # TODO: remove above line and implement your own Hough Transformation:
    # acc = ...
    return acc
示例#38
0
def circle(image):
    edges = canny(image, sigma=3, low_threshold=10, high_threshold=50)

    # Detect two radii
    hough_radii = np.arange(20, 35, 2)
    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)

    # 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,
                                        shape=image.shape)
        image[circy, circx] = (220, 20, 20)

    ax.imshow(image, cmap=plt.cm.gray)
    plt.show()
示例#39
0
def create_circle_center(img_shape, centers, radius=10):
    """ create initialisation from centres as small circles

    :param img_shape:
    :param [[int, int]] centers:
    :param int radius:
    :return:
    """
    mask_circle = np.zeros(img_shape, dtype=int)
    mask_perimeter = np.zeros(img_shape, dtype=int)
    center_circles = list()
    for i, pos in enumerate(centers):
        rr, cc = draw.circle(int(pos[0]),
                             int(pos[1]),
                             radius,
                             shape=img_shape[:2])
        mask_circle[rr, cc] = i + 1
        rr, cc = draw.circle_perimeter(int(pos[0]),
                                       int(pos[1]),
                                       radius,
                                       shape=img_shape[:2])
        mask_perimeter[rr, cc] = i + 1
        center_circles.append(np.array([rr, cc]).transpose())
    return center_circles, mask_circle, mask_perimeter
示例#40
0
def getCellsInPlane(shape, points, order, prefix, index, plsmns):
    cellsImg = np.zeros(shape, dtype=np.uint16)
    blobs = []
    col = order[0]
    for i in range(len(points[:, col])):
        point = int(np.round(points[i, col]))
        if index - plsmns <= point <= index + plsmns:
            blobs.append([points[i, :]])
    blobs = np.concatenate(blobs)
    print(len(blobs))
    for i in range(len(blobs)):
        y = int(np.round(blobs[i, order[1]]))
        x = int(np.round(blobs[i, order[2]]))
        r, c, rad = y, x, 1
        rr, cc = circle_perimeter(r, c, rad)
        try:
            cellsImg[rr, cc] = 65535
        except IndexError:
            print('point {}, {}, out of range'.format(y, x))

    saveName = prefix + '_' + str(col) + '_' + str(index) + '.tif'
    with TiffWriter(saveName) as tif:
        tif.save(cellsImg)
    return cellsImg
示例#41
0
def find_iris(image, pupil, **kwargs):
    buffer = 20
    # run canny
    image = filter.canny(image, sigma=1, low_threshold=10, high_threshold=50)
    cx, cy, radius = pupil

    segments = get_segments(17, step=0.05)
    # get ray directions
    directions = zip(map(cos, segments[0]), map(sin, segments[0]))
    shape = image.shape
    points = []
    for d in directions:
        start = (cx + (radius + buffer) * d[0], cy + (radius + buffer) * d[1])
        ray = Ray(image, start, d)
        point = ray.fire()
        if point != None:
            points.append(point)

    for p in points:
        x, y = circle_perimeter(int(p[0]), int(p[1]), 3)
        rgb[x, y] = (220, 40, 40)

    e = Ellipse().fit_with_center(None, points)
    return image, points, e
def remove_optic_disk(image):

    roi = getROI(image)
    preprocessed_roi = preprocess(roi)

    # im2, contours, hierarchy = cv2.findContours(segmented, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    ##We get our ROI and then we preprocess it.
    ##After preprocess, we apply a canny border algorithm
    ##We dilate the borders in order to make it easy to detect with hough

    edged = canny(preprocessed_roi, 0.22)
    kernel = np.ones((3, 3), np.uint8)
    edged = cv2.dilate(edged, kernel, iterations=3)
    accums, cx, cy, radii = hough(edged, 55, 80)
    for center_y, center_x, radius in zip(cy, cx, radii):
        circy, circx = circle_perimeter(center_y, center_x, radius)
        try:
            roi[circy, circx] = (220, 20, 20)
        except:
            continue
    #
    init = np.array([circx, circy]).T

    return preprocessed_roi, roi
示例#43
0
def extraCredit():
    egg_img = np.array(imread('./egg.jpg'))
    jupiter_img = np.array(imread('./jupiter.jpg'))
    draw_color = np.array([255, 255, 0])

    radius = [2, 12]
    sigma = 2
    threshold = 0.65
    use_gradient = False
    bin_scale = 1
    epsilon = 0.05

    centers, hough_space = detect_circles(egg_img,
                                          radius,
                                          use_Grad=use_gradient,
                                          threshold=threshold,
                                          sigma=sigma,
                                          bin_scale=bin_scale,
                                          epsilon=epsilon,
                                          hough=True)

    hough_img = hough_space.astype(int).sum(axis=0)
    scale_factor = 255 / hough_img.max()
    hough_img = (scale_factor * hough_img).astype(np.uint8)
    circled_img = egg_img.copy()
    for center in centers:
        circle = circle_perimeter(center[1],
                                  center[2],
                                  radius=center[0],
                                  shape=img.shape)
        circled_img[circle] = draw_color

    plt.rcParams['figure.figsize'] = [16, 10]
    fig, axs = plt.subplots(1, 2)
    axs[0].imshow(circled_img)
    axs[1].imshow(hough_img, cmap='gray')
    axs[0].title.set_text('Circles Marked')
    axs[1].title.set_text('Accumulator Array')
    plt.show()

    hough_img = hough_space
    hough_img_threshold = hough_img.copy()
    hough_img_threshold[hough_img < hough_img.max() * threshold] = 0
    hough_img_threshold[hough_img_threshold > 0] = 1
    hough_img_threshold = hough_img_threshold.astype(bool)

    labels = measure.label(hough_img_threshold, background=0)
    count = labels.max()
    centers = []
    for i in range(1, count + 1):
        centers.append((np.mean(np.array(np.where(labels == i)), axis=1) /
                        bin_scale).astype(int))
    centers = np.array(centers)

    circled_img = egg_img.copy()
    for center in centers:
        circle = circle_perimeter(center[1],
                                  center[2],
                                  radius=center[0] + radius[0],
                                  shape=img.shape)
        circled_img[circle] = draw_color

    print('Circle Count:', count)
示例#44
0
def detect_circles(img,
                   radius,
                   use_Grad=False,
                   sigma=1.0,
                   threshold=0.8,
                   epsilon='auto',
                   bin_scale=1,
                   hough=False):

    # Detect edges
    img_gray = img_as_float(rgb2gray(img))
    edges = canny(img_gray, sigma=sigma)

    #For examples using gradient
    if use_Grad:
        g_x = convolve(img_gray, np.array([[1, -1]]), mode='wrap')
        g_y = convolve(img_gray, np.array([[1], [-1]]), mode="wrap")
        g_x[g_x == 0] = 1e-10
        g_direct = np.arctan(g_y / g_x)

    # Detect circles
    flag = False
    if type(radius) is not list:
        flag = True
        radius = [radius, radius + 1]
    temp_0 = radius[1] - radius[0]
    temp_1 = int(img.shape[0] * bin_scale)
    temp_2 = int(img.shape[1] * bin_scale)
    votes = np.zeros((temp_0, temp_1, temp_2))
    for rad in range(radius[0], radius[1]):
        hough_space = np.zeros((temp_1, temp_2))
        for row in range(img.shape[0]):
            for col in range(img.shape[1]):
                if edges[row, col] != 0:
                    if not use_Grad and epsilon == 'auto':
                        v = np.linspace(0, 2 * np.pi, 6 * rad)
                    elif not use_Grad and epsilon != 'auto':
                        v = np.arange(0, 2 * np.pi, epsilon)
                    if use_Grad:
                        theta = g_direct[row, col]
                        v = np.array([theta, theta - np.pi])
                    for theta in v:
                        vote_x = int(
                            round(col + rad * np.cos(theta)) * bin_scale)
                        vote_y = int(
                            round(row + rad * np.sin(theta)) * bin_scale)
                        if vote_x >= 0 and vote_x < hough_space.shape[
                                1] and vote_y >= 0 and vote_y < hough_space.shape[
                                    0]:
                            hough_space[vote_y,
                                        vote_x] = hough_space[vote_y,
                                                              vote_x] + 1
        votes[rad - radius[0]] = hough_space

    if flag:
        hough_space = votes[0]
        centers = (np.transpose(
            np.array(np.where(hough_space >= hough_space.max() * threshold))) /
                   bin_scale).astype(int)
        if not hough:
            return centers
        return centers, hough_space
    else:
        centroid = (np.transpose(
            np.array(np.where(votes >= votes.max() * threshold))) /
                    bin_scale).astype(int)
        centroid[:, 0] = centroid[:, 0] + radius[0]
        if not hough:
            return centroid
        return centroid, votes
    circled_img = img.copy()
    for center in centers:
        circle = circle_perimeter(center[0],
                                  center[1],
                                  radius=radius,
                                  shape=img.shape)
        circled_img[circle] = draw_color
    imsave('reduced_' + save_name_circled, circled_img)

    print('Circle Count:', count)
示例#45
0
 epsilon = 0.1
 circled_img = img.copy()
 centers, votes = detect_circles(img,
                                 radius,
                                 use_Grad=use_Grad,
                                 threshold=threshold,
                                 sigma=sigma,
                                 bin_scale=bin_scale,
                                 epsilon=epsilon,
                                 hough=True)
 scale_factor = 255 / votes.max()
 hough_img = (scale_factor * votes).astype(np.uint8)
 labels = measure.label(hough_img_threshold, background=0)
 count = labels.max()
 for center in centers:
     circle = circle_perimeter(center[0],
                               center[1],
                               radius=radius,
                               shape=img.shape)
     circled_img[circle] = draw_color
 plt.rcParams['figure.figsize'] = [16, 10]
 fig, axs = plt.subplots(1, 2)
 print(count)
 axs[0].imshow(circled_img)
 axs[1].imshow(hough_img, cmap='gray')
 axs[0].title.set_text('Circles Marked')
 axs[1].title.set_text('Accumulator Array')
 plt.show()
 # For grader, feel free to uncomment and run extraCredit,
 # I put the parameters for egg.jpg only, you could change filename
 # extraCredit()
示例#46
0
def draw_circle_perimeter(frame, center_x, center_y, radius, color):
    cy, cx = circle_perimeter(int(center_y), int(center_x), int(radius))

    cy, cx = _coords_inside_image(cy, cx, frame.shape)
    frame[cy, cx] = color
def test_img_plot(
    img_name,
    img_read_loc,
    img_read_format='.tif',
    img_save_loc=None,
    img_save_format='png',
    tly=123,
    bly=415,
    bry=427,
    trry=136,
    part_cx=False,
    part_cy=False,
    draw_bpe_color=None,
    draw_particle_color=None,
    draw_particle=True,
    draw_bpe=True,
    show=True,
    save=False,
    pause_time=3,
    um_per_pix=1,
    bf=35,
    draw_particle_radius=10,
):

    # other variables
    lr_shift_y = 14  # angle of image
    w = 550  # channel width

    # read file path
    img_name = img_name + '_X1'
    image_read = img_read_loc + img_name + img_read_format

    # load image
    img = io.imread(image_read)

    # calculate image shape
    img_dims = np.shape(img)

    # calculate BPE locations
    centerline = int(
        np.round((np.mean([tly, bly]) + np.mean([bry, trry])) / 2, 0))
    bpe_leadedge_centerline = int(np.round((np.mean([tly, bly]))))

    # draw bpe rectangle
    if draw_bpe == True:

        # choose color
        if draw_bpe_color == None:
            draw_bpe_color = int(np.round(bf * np.mean(img), 0))

        # organize particle data
        xloc = int(np.round((part_cx) / um_per_pix, 0))
        yloc = int(np.round((part_cy) / um_per_pix, 0))

        # draw rectangle
        poly = np.array(
            ((yloc - thresh, xloc - thresh), (yloc - thresh, xloc + thresh),
             (yloc + thresh, xloc + thresh), (yloc + thresh, xloc - thresh),
             (yloc - thresh, xloc - thresh)))

        rr, cc = polygon_perimeter(poly[:, 0], poly[:, 1], img.shape)
        img[rr, cc] = draw_bpe_color

        # rescale back to micron coordinates and adjust image name
        xloc = int(np.round(xloc * um_per_pix, 0))
        yloc = int(np.round(yloc * um_per_pix, 0))

        # draw centerline line
        #rr, cc = line(centerline, 0, centerline, 511)
        #img[rr, cc] = draw_bpe_color

        # draw wall lines
        rr, cc = line(
            int(np.round(centerline + (w / um_per_pix) / 2, 0) - 6), 0,
            int(
                np.round(centerline + (w / um_per_pix) / 2 + lr_shift_y, 0) -
                6), 511)
        img[rr, cc] = draw_bpe_color

        rr, cc = line(
            int(np.round(centerline - (w / um_per_pix) / 2, 0) - 6), 0,
            int(
                np.round(centerline - (w / um_per_pix) / 2 + lr_shift_y, 0) -
                6), 511)
        img[rr, cc] = draw_bpe_color

    # draw particle
    if draw_particle == True:

        # choose color
        if draw_particle_color == None:
            draw_particle_color = int(np.round(np.min(img), 0))

        # organize particle data
        xloc = int(np.round((part_cx) / um_per_pix, 0))
        yloc = int(np.round((part_cy) / um_per_pix, 0))

        # create circle perimeter
        rr, cc = circle_perimeter(yloc, xloc, draw_particle_radius)
        rr = np.where(rr > 511, 511, rr)
        rr = np.where(rr < 0, 0, rr)
        cc = np.where(cc > 511, 511, cc)
        cc = np.where(cc < 0, 0, cc)
        img[rr, cc] = draw_particle_color

        # rescale back to micron coordinates
        xloc = int(np.round(xloc * um_per_pix, 0))
        yloc = int(np.round(yloc * um_per_pix, 0))

    # adjust image name
    img_name = "Image-Particle_X" + str(xloc) + '.Y' + str(yloc)

    # create figure
    fig, ax = plt.subplots(figsize=(8, 8))
    ax.imshow(img * bf,
              cmap='gray',
              extent=(0, img_dims[0] * um_per_pix, img_dims[1] * um_per_pix,
                      0))
    ax.set_title(img_name)
    plt.xlabel('Axial - Channel (um)')
    plt.ylabel('Transverse - Channel (um)')
    plt.grid(color='dimgray', alpha=0.25, linestyle='-', linewidth=0.25)

    # display
    if show == True:
        plt.show()
        plt.pause(pause_time)

    # save
    if save == True:
        image_save = img_save_loc + img_name + '.' + img_save_format
        #plt.imsave(image_save, img * bf, format=img_save_format, cmap='gray')
        #plt_img_save = img_save_loc + img_name + '_plt.' + img_save_format
        print(image_save)
        plt.savefig(image_save, format=img_save_format)

    plt.close(fig=None)

    # return centerline
    return centerline
示例#48
0
def png_set_color(img, x, y, d):
    """Draw the nodule marker box."""
    img_rgb = np.array(Image.fromarray(img).convert("RGB"))
    rr, cc = draw.circle_perimeter(y, x, d // 2 + 4)
    draw.set_color(img_rgb, [rr, cc], [0, 0, 255], alpha=1.0)
edges = canny(image, sigma=3, low_threshold=10, high_threshold=50)

# Detect two radii
hough_radii = np.arange(20, 35, 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)
    image[circy, circx] = (220, 20, 20)

ax.imshow(image, cmap=plt.cm.gray)
plt.show()

######################################################################
# Ellipse detection
# =================
#
# In this second example, the aim is to detect the edge of a coffee cup.
# Basically, this is a projection of a circle, i.e. an ellipse. The problem
# to solve is much more difficult because five parameters have to be
# determined, instead of three for circles.
#
# Algorithm overview
示例#50
0
def detect_circles(np_image):
    """
    Uses Hough transform to detect the radii and the
    centres of the "blobs" indicating the point of
    contact between the spheres
    """
    import numpy as np
    import pylab as pl
    from skimage.transform import hough_circle
    from skimage.feature import peak_local_max
    from skimage.draw import circle_perimeter

    pl.close('all')

    min_rad = int(max(np_image.shape[0], np_image.shape[1]) / 4.0)
    max_rad = int(max(np_image.shape[0], np_image.shape[1]) / 2.0)
    step = 1

    hough_radii = np.arange(min_rad, max_rad, step, np.float64)
    hough_res = hough_circle(np_image, hough_radii)

    centers = []
    accums = []
    radii = []
    circles = []  # to get the outlines of the circles
    C = [
    ]  # to get the centres of the circles, in relation to the different areas

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

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

    #np_image[circles[0][0], circles[0][1]] = 0

#     pl.imshow(np_image)
#     pl.title('Circle detection on real image using Hough transform\n- optimised with image labelling algorithm -', fontdict={'fontsize': 20,'verticalalignment': 'baseline','horizontalalignment': 'center'})
#     pl.colorbar()
#     pl.show()

#     C_cp = C
#     C = []
#
#     if radius % 2 != 0:
#         C.append((C_cp[0][0] + 0.5, C_cp[0][1] + 0.5))
#     elif radius % 2 != 0:
#         C.append((C_cp[0][0] + 0.5, C_cp[0][1]))
#     elif radius % 2 != 0:
#         C.append((C_cp[0][0], C_cp[0][1] + 0.5))
#     else:
#         C.append((C_cp[0][0], C_cp[0][1]))

    return C
示例#51
0
def daisy(img, step=4, radius=15, rings=3, histograms=8, orientations=8,
          normalization='l1', sigmas=None, ring_radii=None, visualize=False):
    '''Extract DAISY feature descriptors densely for the given image.

    DAISY is a feature descriptor similar to SIFT formulated in a way that
    allows for fast dense extraction. Typically, this is practical for
    bag-of-features image representations.

    The implementation follows Tola et al. [1]_ but deviate on the following
    points:

      * Histogram bin contribution are smoothed with a circular Gaussian
        window over the tonal range (the angular range).
      * The sigma values of the spatial Gaussian smoothing in this code do not
        match the sigma values in the original code by Tola et al. [2]_. In
        their code, spatial smoothing is applied to both the input image and
        the center histogram. However, this smoothing is not documented in [1]_
        and, therefore, it is omitted.

    Parameters
    ----------
    img : (M, N) array
        Input image (greyscale).
    step : int, optional
        Distance between descriptor sampling points.
    radius : int, optional
        Radius (in pixels) of the outermost ring.
    rings : int, optional
        Number of rings.
    histograms  : int, optional
        Number of histograms sampled per ring.
    orientations : int, optional
        Number of orientations (bins) per histogram.
    normalization : [ 'l1' | 'l2' | 'daisy' | 'off' ], optional
        How to normalize the descriptors

          * 'l1': L1-normalization of each descriptor.
          * 'l2': L2-normalization of each descriptor.
          * 'daisy': L2-normalization of individual histograms.
          * 'off': Disable normalization.

    sigmas : 1D array of float, optional
        Standard deviation of spatial Gaussian smoothing for the center
        histogram and for each ring of histograms. The array of sigmas should
        be sorted from the center and out. I.e. the first sigma value defines
        the spatial smoothing of the center histogram and the last sigma value
        defines the spatial smoothing of the outermost ring. Specifying sigmas
        overrides the following parameter.

            ``rings = len(sigmas) - 1``

    ring_radii : 1D array of int, optional
        Radius (in pixels) for each ring. Specifying ring_radii overrides the
        following two parameters.

            ``rings = len(ring_radii)``
            ``radius = ring_radii[-1]``

        If both sigmas and ring_radii are given, they must satisfy the
        following predicate since no radius is needed for the center
        histogram.

            ``len(ring_radii) == len(sigmas) + 1``

    visualize : bool, optional
        Generate a visualization of the DAISY descriptors

    Returns
    -------
    descs : array
        Grid of DAISY descriptors for the given image as an array
        dimensionality  (P, Q, R) where

            ``P = ceil((M - radius*2) / step)``
            ``Q = ceil((N - radius*2) / step)``
            ``R = (rings * histograms + 1) * orientations``

    descs_img : (M, N, 3) array (only if visualize==True)
        Visualization of the DAISY descriptors.

    References
    ----------
    .. [1] Tola et al. "Daisy: An efficient dense descriptor applied to wide-
           baseline stereo." Pattern Analysis and Machine Intelligence, IEEE
           Transactions on 32.5 (2010): 815-830.
    .. [2] http://cvlab.epfl.ch/alumni/tola/daisy.html
    '''

    # Validate image format.
    if img.ndim > 2:
        raise ValueError('Only grey-level images are supported.')
    if img.dtype.kind != 'f':
        img = img_as_float(img)

    # Validate parameters.
    if sigmas is not None and ring_radii is not None \
            and len(sigmas) - 1 != len(ring_radii):
        raise ValueError('len(sigmas)-1 != len(ring_radii)')
    if ring_radii is not None:
        rings = len(ring_radii)
        radius = ring_radii[-1]
    if sigmas is not None:
        rings = len(sigmas) - 1
    if sigmas is None:
        sigmas = [radius * (i + 1) / float(2 * rings) for i in range(rings)]
    if ring_radii is None:
        ring_radii = [radius * (i + 1) / float(rings) for i in range(rings)]
    if normalization not in ['l1', 'l2', 'daisy', 'off']:
        raise ValueError('Invalid normalization method.')

    # Compute image derivatives.
    dx = np.zeros(img.shape)
    dy = np.zeros(img.shape)
    dx[:, :-1] = np.diff(img, n=1, axis=1)
    dy[:-1, :] = np.diff(img, n=1, axis=0)

    # Compute gradient orientation and magnitude and their contribution
    # to the histograms.
    grad_mag = sqrt(dx ** 2 + dy ** 2)
    grad_ori = arctan2(dy, dx)
    orientation_kappa = orientations / pi
    orientation_angles = [2 * o * pi / orientations - pi
                          for o in range(orientations)]
    hist = np.empty((orientations,) + img.shape, dtype=float)
    for i, o in enumerate(orientation_angles):
        # Weigh bin contribution by the circular normal distribution
        hist[i, :, :] = exp(orientation_kappa * cos(grad_ori - o))
        # Weigh bin contribution by the gradient magnitude
        hist[i, :, :] = np.multiply(hist[i, :, :], grad_mag)

    # Smooth orientation histograms for the center and all rings.
    sigmas = [sigmas[0]] + sigmas
    hist_smooth = np.empty((rings + 1,) + hist.shape, dtype=float)
    for i in range(rings + 1):
        for j in range(orientations):
            hist_smooth[i, j, :, :] = gaussian_filter(hist[j, :, :],
                                                      sigma=sigmas[i])

    # Assemble descriptor grid.
    theta = [2 * pi * j / histograms for j in range(histograms)]
    desc_dims = (rings * histograms + 1) * orientations
    descs = np.empty((desc_dims, img.shape[0] - 2 * radius,
                      img.shape[1] - 2 * radius))
    descs[:orientations, :, :] = hist_smooth[0, :, radius:-radius,
                                             radius:-radius]
    idx = orientations
    for i in range(rings):
        for j in range(histograms):
            y_min = radius + int(round(ring_radii[i] * sin(theta[j])))
            y_max = descs.shape[1] + y_min
            x_min = radius + int(round(ring_radii[i] * cos(theta[j])))
            x_max = descs.shape[2] + x_min
            descs[idx:idx + orientations, :, :] = hist_smooth[i + 1, :,
                                                              y_min:y_max,
                                                              x_min:x_max]
            idx += orientations
    descs = descs[:, ::step, ::step]
    descs = descs.swapaxes(0, 1).swapaxes(1, 2)

    # Normalize descriptors.
    if normalization != 'off':
        descs += 1e-10
        if normalization == 'l1':
            descs /= np.sum(descs, axis=2)[:, :, np.newaxis]
        elif normalization == 'l2':
            descs /= sqrt(np.sum(descs ** 2, axis=2))[:, :, np.newaxis]
        elif normalization == 'daisy':
            for i in range(0, desc_dims, orientations):
                norms = sqrt(np.sum(descs[:, :, i:i + orientations] ** 2,
                                    axis=2))
                descs[:, :, i:i + orientations] /= norms[:, :, np.newaxis]

    if visualize:
        descs_img = skimage.color.gray2rgb(img)
        for i in range(descs.shape[0]):
            for j in range(descs.shape[1]):
                # Draw center histogram sigma
                color = (1, 0, 0)
                desc_y = i * step + radius
                desc_x = j * step + radius
                coords = draw.circle_perimeter(desc_y, desc_x, int(sigmas[0]))
                draw.set_color(descs_img, coords, color)
                max_bin = np.max(descs[i, j, :])
                for o_num, o in enumerate(orientation_angles):
                    # Draw center histogram bins
                    bin_size = descs[i, j, o_num] / max_bin
                    dy = sigmas[0] * bin_size * sin(o)
                    dx = sigmas[0] * bin_size * cos(o)
                    coords = draw.line(desc_y, desc_x, int(desc_y + dy),
                                       int(desc_x + dx))
                    draw.set_color(descs_img, coords, color)
                for r_num, r in enumerate(ring_radii):
                    color_offset = float(1 + r_num) / rings
                    color = (1 - color_offset, 1, color_offset)
                    for t_num, t in enumerate(theta):
                        # Draw ring histogram sigmas
                        hist_y = desc_y + int(round(r * sin(t)))
                        hist_x = desc_x + int(round(r * cos(t)))
                        coords = draw.circle_perimeter(hist_y, hist_x,
                                                       int(sigmas[r_num + 1]))
                        draw.set_color(descs_img, coords, color)
                        for o_num, o in enumerate(orientation_angles):
                            # Draw histogram bins
                            bin_size = descs[i, j, orientations + r_num *
                                             histograms * orientations +
                                             t_num * orientations + o_num]
                            bin_size /= max_bin
                            dy = sigmas[r_num + 1] * bin_size * sin(o)
                            dx = sigmas[r_num + 1] * bin_size * cos(o)
                            coords = draw.line(hist_y, hist_x,
                                               int(hist_y + dy),
                                               int(hist_x + dx))
                            draw.set_color(descs_img, coords, color)
        return descs, descs_img
    else:
        return descs
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)
    centers.extend(peaks)
    accums.extend(h[peaks[:, 0], peaks[:, 1]])
    radii.extend([radius, radius])

# 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)
"""
.. image:: PLOT2RST.current_figure

Ellipse detection
=================

In this second example, the aim is to detect the edge of a coffee cup.
Basically, this is a projection of a circle, i.e. an ellipse.
The problem to solve is much more difficult because five parameters have to be
determined, instead of three for circles.

img = io.imread('./circle.png')
image_gray = color.rgb2gray(img)

im = ndi.gaussian_filter(image_gray, 1.5, mode="reflect")

# blur = gaussian(image_gray,0.2)
im = img_as_ubyte(im[0:260, 70:280])
edges = canny(im, sigma=2, low_threshold=0.55, high_threshold=0.8)

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

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

# Draw them
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(20, 20))
ax.set_title('Detected Circles', fontsize=50)  # title of plot
image = color.gray2rgb(img[0:260, 70:280])
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] = (220, 20, 20)

ax.imshow(image, cmap=plt.cm.gray)
plt.show()
示例#54
0
def mask_to_food_contour(mask, n_bins=90, frac_lowess=0.05, is_debug=False):
    '''
    Estimate the food contour from a binary mask. 
    1) Get the best the best fit to a circle using the hough transform.
    2) Transform the mask into polar coordinates centered in the fitted circle.
    3) Get the closest point to the circle using 2*n_bins angles.
    4) Smooth using lowess fitting (good to ignore outliers) to estimate the food contour.
    5) Transform back into cartesian coordinates.
    '''
    #%%
    h_res = get_best_circles(mask.copy())
    _, cy0, cx0, r0 = h_res[0]

    (px, py) = np.where(skeletonize(mask))

    xx = px - cx0
    yy = py - cy0

    del_r = np.sqrt(xx * xx + yy * yy) - r0
    theta = np.arctan2(xx, yy)

    theta_d = np.round((theta / np.pi) * n_bins).astype(np.int)

    #g = {k:[] for k in range(-n_bins, n_bins+1)}
    g = {k: [] for k in np.unique(theta_d)}
    for k, dr in zip(theta_d, del_r):
        g[k].append(dr)

    _get_min = lambda g: min(g, key=lambda x: abs(x)) if g else np.nan
    tg, min_dr = zip(*[(k, _get_min(g)) for k, g in g.items()])

    theta_s = np.array(tg) * np.pi / n_bins

    #increase the range for the interpolation
    theta_i = np.hstack((theta_s - 2 * np.pi, theta_s, theta_s + 2 * np.pi))

    r_s = np.hstack((min_dr, min_dr, min_dr))

    out = lowess(r_s, theta_i, frac=frac_lowess)

    #win_frac = 1/3
    #filt_w = round(n_bins*win_frac)
    #filt_w = filt_w+1 if filt_w % 2 == 0 else filt_w
    #r_s = medfilt(r_s, filt_w)
    f = interp1d(out[:, 0], out[:, 1])

    theta_new = np.linspace(-np.pi, np.pi, 480)
    r_new = f(theta_new) + r0

    circy = r_new * np.cos(theta_new) + cy0
    circx = r_new * np.sin(theta_new) + cx0
    #%%
    if is_debug:
        from skimage.draw import circle_perimeter
        import matplotlib.pylab as plt

        plt.figure(figsize=(5, 5))
        for ii, (acc, cx, cy, cr) in enumerate(h_res[0:1]):
            #plt.subplot(3,3,ii+1)
            plt.imshow(mask)
            cpy, cpx = circle_perimeter(cy, cx, cr)
            plt.plot(cpx, cpy, '.r')

        plt.figure()
        plt.plot(theta_d, del_r, '.')
        plt.plot(tg, min_dr)

        plt.figure()
        plt.plot(theta_i, r_s, '.')
        plt.plot(out[:, 0], out[:, 1], '.')

    #%%
    return circx, circy, h_res[0]
示例#55
0
def auto_find_center_rings(avg_img,
                           sigma=1,
                           no_rings=4,
                           min_samples=3,
                           residual_threshold=1,
                           max_trials=1000):
    """This will find the center of the speckle pattern and the radii of the
    most intense rings.

    Parameters
    ----------
    avg_img : 2D array
        shape of the image
    sigma : float, optional
        Standard deviation of the Gaussian filter.
    no_rings : int, optional
        number of rings
    min_sample : int, optional
        The minimum number of data points to fit a model to.
    residual_threshold : float, optional
        Maximum distance for a data point to be classified as an inlier.
    max_trials : int, optional
        Maximum number of iterations for random sample selection.

    Returns
    -------
    center : tuple
        center co-ordinates of the speckle pattern
    image : 2D array
        Indices of pixels that belong to the rings,
        directly index into an array
    radii : list
        values of the radii of the rings

    Note
    ----
    scikit-image ransac method(http://www.imagexd.org/tutorial/lessons/1_ransac.html)
    is used to automatically find the center and the most intense rings.
    """

    image = img_as_float(color.rgb2gray(avg_img))
    edges = feature.canny(image, sigma)
    coords = np.column_stack(np.nonzero(edges))
    edge_pts_xy = coords[:, ::-1]
    radii = []

    for i in range(no_rings):
        model_robust, inliers = ransac(edge_pts_xy,
                                       CircleModel,
                                       min_samples,
                                       residual_threshold,
                                       max_trials=max_trials)
        if i == 0:
            center = int(model_robust.params[0]), int(model_robust.params[1])
        radii.append(model_robust.params[2])

        rr, cc = draw.circle_perimeter(center[1],
                                       center[0],
                                       int(model_robust.params[2]),
                                       shape=image.shape)
        image[rr, cc] = i + 1
        edge_pts_xy = edge_pts_xy[-inliers]

    return center, image, radii
示例#56
0
    def get(self, idx):
        img = np.random.randn(*(self.dim + (3, ))) / 5

        ri1, ri2, ri3, ri4, ri5, ri6 = np.sign(np.random.randint(
            -100, 100)) * ((np.random.rand() * 2) + .5), np.sign(
                np.random.randint(-100, 100)) * (
                    (np.random.rand() * 2) + .5), (np.random.rand() * 4) + 3, (
                        np.random.rand() * 4) + 3, np.sign(
                            np.random.randint(-100, 100)) * (
                                (np.random.rand() * 2) + .5), np.sign(
                                    np.random.randint(-100, 100)) * (
                                        (np.random.rand() * 2) + .5)
        x = np.zeros(self.dim)
        x[:, :] = np.arange(img.shape[0])[np.newaxis, :]
        y = x.transpose()
        img += (np.sin(
            np.sqrt((x * ri1)**2 + ((self.dim[1] - y) * ri2)**2) * ri3 *
            np.pi / self.dim[0]))[..., np.newaxis]
        img += (np.sin(
            np.sqrt((x * ri5)**2 + ((self.dim[1] - y) * ri6)**2) * ri4 *
            np.pi / self.dim[1]))[..., np.newaxis]
        img = gaussian(np.clip(img, 0.1, 1), sigma=.8)
        circles = []
        cmps = []
        while len(circles) < self.n_ellips:
            mp = np.random.randint(self.min_r, self.dim[0] - self.min_r, 2)
            too_close = False
            for cmp in cmps:
                if np.linalg.norm(cmp - mp) < self.min_dist:
                    too_close = True
            if too_close:
                continue
            r = np.random.randint(self.min_r, self.max_r, 2)
            circles.append(draw.circle(mp[0], mp[1], r[0], shape=self.dim))
            cmps.append(mp)

        polys = []
        while len(polys) < self.n_polys:
            mp = np.random.randint(self.min_r, self.dim[0] - self.min_r, 2)
            too_close = False
            for cmp in cmps:
                if np.linalg.norm(cmp - mp) < self.min_dist // 2:
                    too_close = True
            if too_close:
                continue
            circle = draw.circle_perimeter(mp[0], mp[1], self.max_r)
            poly_vert = np.random.choice(len(circle[0]),
                                         np.random.randint(3, 6),
                                         replace=False)
            polys.append(
                draw.polygon(circle[0][poly_vert],
                             circle[1][poly_vert],
                             shape=self.dim))
            cmps.append(mp)

        rects = []
        while len(rects) < self.n_rect:
            mp = np.random.randint(self.min_r, self.dim[0] - self.min_r, 2)
            _len = np.random.randint(self.min_r // 2, self.max_r, (2, ))
            too_close = False
            for cmp in cmps:
                if np.linalg.norm(cmp - mp) < self.min_dist:
                    too_close = True
            if too_close:
                continue
            start = (mp[0] - _len[0], mp[1] - _len[1])
            rects.append(
                draw.rectangle(start,
                               extent=(_len[0] * 2, _len[1] * 2),
                               shape=self.dim))
            cmps.append(mp)

        for poly in polys:
            color = np.random.rand(3)
            while np.linalg.norm(color - self.ellips_color
                                 ) < self.col_diff or np.linalg.norm(
                                     color - self.rect_color) < self.col_diff:
                color = np.random.rand(3)
            img[poly[0], poly[1], :] = color
            img[poly[0], poly[1], :] += np.random.randn(len(poly[1]), 3) / 5

        cols = np.random.choice(np.arange(4, 11, 1).astype(np.float) / 10,
                                self.n_ellips,
                                replace=False)
        for i, ellipse in enumerate(circles):
            ri1, ri2, ri3, ri4, ri5, ri6 = np.sign(np.random.randint(
                -100, 100)) * ((np.random.rand() * 4) + 7), np.sign(
                    np.random.randint(-100, 100)) * (
                        (np.random.rand() * 4) +
                        7), (np.random.rand() +
                             1) * 3, (np.random.rand() + 1) * 3, np.sign(
                                 np.random.randint(-100, 100)) * (
                                     (np.random.rand() * 4) + 7), np.sign(
                                         np.random.randint(-100, 100)) * (
                                             (np.random.rand() * 4) + 7)
            img[ellipse[0], ellipse[1], :] = np.array([cols[i], 0.0, 0.0])
            img[ellipse[0],
                ellipse[1], :] += np.array([1.0, 1.0, 0.0]) * ((np.sin(
                    np.sqrt((x[ellipse[0], ellipse[1]] * ri5)**2 + (
                        (self.dim[1] - y[ellipse[0], ellipse[1]]) * ri2)**2) *
                    ri3 * np.pi / self.dim[0]))[..., np.newaxis] * 0.15) + 0.2
            img[ellipse[0],
                ellipse[1], :] += np.array([1.0, 1.0, 0.0]) * ((np.sin(
                    np.sqrt((x[ellipse[0], ellipse[1]] * ri6)**2 + (
                        (self.dim[1] - y[ellipse[0], ellipse[1]]) * ri1)**2) *
                    ri4 * np.pi / self.dim[1]))[..., np.newaxis] * 0.15) + 0.2
            # img[ellipse[0], ellipse[1], :] += np.random.randn(len(ellipse[1]), 3) / 10

        cols = np.random.choice(np.arange(4, 11, 1).astype(np.float) / 10,
                                self.n_rect,
                                replace=False)
        for rect in rects:
            ri1, ri2, ri3, ri4, ri5, ri6 = np.sign(np.random.randint(
                -100, 100)) * ((np.random.rand() * 4) + 7), np.sign(
                    np.random.randint(-100, 100)) * (
                        (np.random.rand() * 4) +
                        7), (np.random.rand() +
                             1) * 3, (np.random.rand() + 1) * 3, np.sign(
                                 np.random.randint(-100, 100)) * (
                                     (np.random.rand() * 4) + 7), np.sign(
                                         np.random.randint(-100, 100)) * (
                                             (np.random.rand() * 4) + 7)
            img[rect[0], rect[1], :] = np.array([0.0, 0.0, cols[i]])
            img[rect[0], rect[1], :] += np.array([1.0, 1.0, 0.0]) * ((np.sin(
                np.sqrt((x[rect[0], rect[1]] * ri5)**2 +
                        ((self.dim[1] - y[rect[0], rect[1]]) * ri2)**2) * ri3 *
                np.pi / self.dim[0]))[..., np.newaxis] * 0.15) + 0.2
            img[rect[0], rect[1], :] += np.array([1.0, 1.0, 0.0]) * ((np.sin(
                np.sqrt((x[rect[0], rect[1]] * ri1)**2 +
                        ((self.dim[1] - y[rect[0], rect[1]]) * ri6)**2) * ri4 *
                np.pi / self.dim[1]))[..., np.newaxis] * 0.15) + 0.2
            # img[rect[0], rect[1], :] += np.random.randn(*(rect[1].shape + (3,)))/10

        img = np.clip(img, 0, 1).astype(np.float32)

        smooth_image = gaussian(img, sigma=.2)

        # shape = np.array(smooth_image.shape[0:2]).astype(np.uint32).tolist()
        # taggedImg = vigra.taggedView(smooth_image, 'xyc')
        # edgeStrength = vigra.filters.structureTensorEigenvalues(taggedImg, 1.5, 1.9)[:, :, 0]
        # edgeStrength = edgeStrength.squeeze()
        # edgeStrength = np.array(edgeStrength).astype(np.float32)
        # seeds = vigra.analysis.localMinima(edgeStrength)
        # seeds = vigra.analysis.labelImageWithBackground(seeds)
        # gridGraph = nifty.graph.undirectedGridGraph(shape)
        # # oversegNodeWeighted = nifty.graph.nodeWeightedWatershedsSegmentation(graph=gridGraph, seeds=seeds.ravel(),
        # #                                                                      nodeWeights=edgeStrength.ravel())
        # # oversegNodeWeighted = oversegNodeWeighted.reshape(shape)
        #
        # gridGraphEdgeStrength = gridGraph.imageToEdgeMap(edgeStrength, mode='sum')
        # np.random.permutation(gridGraphEdgeStrength)
        # oversegEdgeWeightedA = nifty.graph.edgeWeightedWatershedsSegmentation(graph=gridGraph, seeds=seeds.ravel(),
        #                                                                    edgeWeights=gridGraphEdgeStrength)
        # oversegEdgeWeightedA = oversegEdgeWeightedA.reshape(shape)
        # interpixelShape = [2 * s - 1 for s in shape]
        # imgBig = vigra.sampling.resize(taggedImg, interpixelShape)
        # edgeStrength = vigra.filters.structureTensorEigenvalues(imgBig, 2 * 1.5, 2 * 1.9)[:, :, 0]
        # edgeStrength = edgeStrength.squeeze()
        # edgeStrength = np.array(edgeStrength)
        # gridGraphEdgeStrength = gridGraph.imageToEdgeMap(edgeStrength, mode='interpixel')
        # oversegEdgeWeightedB = nifty.graph.edgeWeightedWatershedsSegmentation(
        #     graph=gridGraph,
        #     seeds=seeds.ravel(),
        #     edgeWeights=gridGraphEdgeStrength)
        # oversegEdgeWeightedB = oversegEdgeWeightedB.reshape(shape)

        affinities = get_naive_affinities(smooth_image, offsets)
        affinities[:self.sep_chnl] *= -1
        affinities[:self.sep_chnl] += +1
        affinities[:self.sep_chnl] /= 1.3
        affinities[self.sep_chnl:] *= 1.3
        affinities = np.clip(affinities, 0, 1)
        #
        valid_edges = get_valid_edges((len(self.edge_offsets), ) + self.dim,
                                      self.edge_offsets, self.sep_chnl, None,
                                      False)
        node_labeling, neighbors, cutting_edges, mutexes = compute_mws_segmentation_cstm(
            affinities.ravel(), valid_edges.ravel(), offsets, self.sep_chnl,
            self.dim)

        return img, None
示例#57
0
edges = canny(c, sigma=1, low_threshold=0.1)

fig, ((ax1, ax2),(ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(12, 7), sharex=True, sharey=True)

hough_radii = np.arange(4, 17, 1)
hough_res = hough_circle(edges, hough_radii)
hough_res = hough_circle(s, hough_radii)
Np = 70

accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, min_xdistance=5, min_ydistance=5, total_num_peaks=Np, normalize=True) #,total_num_peaks=3
#print(accums)
image = np.zeros((Nx,Ny))
centers = np.zeros((Nx,Ny))

for center_y, center_x, radius, acc in zip(cy, cx, radii, accums):
    circy, circx = circle_perimeter(center_y, center_x, radius)
    condlisty = [circy < 0, (circy>=0) & (circy<=Ny-1), circy > Ny-1]
    condlistx = [circx < 0, (circx>=0) & (circx<=Nx-1), circx > Nx-1]
    funclist = [lambda x: x+Ny, lambda x: x, lambda x: x-Ny]
    circy = np.piecewise(circy, condlisty, funclist)
    circx = np.piecewise(circx, condlistx, funclist)
    image[center_y,center_x] = acc#1.
    image[circy, circx]= acc#1.
    centers[center_y,center_x] = 1
    
ax1.imshow(image)
ax1.axis('off')
ax1.set_title('noisy image', fontsize=20)

ax2.imshow(centers, cmap=plt.cm.gray)
ax2.axis('off')
    (220, 590),
    (300, 300),
))
rr, cc = polygon(poly[:, 0], poly[:, 1], img.shape)
img[rr, cc, 1] = 1

# fill circle
rr, cc = disk((200, 200), 100, shape=img.shape)
img[rr, cc, :] = (1, 1, 0)

# fill ellipse
rr, cc = ellipse(300, 300, 100, 200, img.shape)
img[rr, cc, 2] = 1

# circle
rr, cc = circle_perimeter(120, 400, 15)
img[rr, cc, :] = (1, 0, 0)

# Bezier curve
rr, cc = bezier_curve(70, 100, 10, 10, 150, 100, 1)
img[rr, cc, :] = (1, 0, 0)

# ellipses
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 4.)
img[rr, cc, :] = (1, 0, 1)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=-math.pi / 4.)
img[rr, cc, :] = (0, 0, 1)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 2.)
img[rr, cc, :] = (1, 1, 1)

ax1.imshow(img)
示例#59
0
xinterp = np.linspace(0, pSEARCH-1, num=len(temp_profile)*100, endpoint=True) 
peak_of_interest = np.zeros([nTw])*np.nan
for i in range(nTw):
    profile[:,i] = raw_wavg_reg_bgsub_reg_circavg_sato[i,ctrd_y, ctrd_x:ctrd_x+20]  
    x = np.linspace(0, pSEARCH-1, num=len(temp_profile), endpoint=True)      
    f = interp1d(x, profile[:,i], kind='cubic')
    profile_interp[:,i] = f(xinterp)
    peaks, properties = find_peaks(profile_interp[:,i], prominence=0.1)
    if peaks.size:
        peak_of_interest[i] = xinterp[peaks[0]]
    else:
        peak_of_interest[i] = np.nan        

tracking_display = np.zeros([nTw,nY,nX])  
for i in range(nTw):
    rr, cc = circle_perimeter(ctrd_y,ctrd_x, (peak_of_interest[i]*1.5).astype('int'), shape=tracking_display[i,:,:].shape)
    tracking_display[i,:,:][rr, cc] = 1 
    

temp_nan_poi = np.zeros([wAVG//2])*np.nan 
peak_of_interest = np.concatenate((
    temp_nan_poi, 
    peak_of_interest, 
    temp_nan_poi),
    axis=0
    ) 

temp_nan_im = np.zeros([wAVG//2,nY,nX])        
raw_wavg_reg_bgsub_reg = np.concatenate((
    temp_nan_im, 
    raw_wavg_reg_bgsub_reg, 
示例#60
0
def mainTurnHR():
    '''1. read img LR and HR'''
    imgLRPath = '../../github/vrn-07231340/examples/scaled/trump_12.jpg'
    imgLR = cv2.imread(imgLRPath)
    imgHRPath = '../../github/vrn-07231340/examples/trump_12.png'
    imgHR = cv2.imread(imgHRPath)
    objPath = '../../github/vrn-07231340/obj/trump_12.obj'

    '''2. img LR --> HR'''
    zRatio = 3
    objLinesHR, vLinesHR, landmarkLR, landmarkHR = lr2hr3DModel(
        imgLR, imgHR, zRatio, objPath)

    '''3. HR: origin 2D landmark --> origin 3D landmark'''
    originLandmark3DList = getLandmark3DHR(landmarkHR, vLinesHR)
    originLandmark3DList = optionChooseZMax(originLandmark3DList)
    faceLandmarkVlines = []
    for (_, _, (_, vLine)) in originLandmark3DList:
        faceLandmarkVlines.append(vLine)

    '''4. HR: collar detection'''
    _, collarPoint = collarDetection(imgHR, minSize=1200, offset=15)

    '''5. HR: hair detection'''
    originHairPoints = hairDetection(imgHR, minSize=20000)

    '''5.1 hair points 不应该全部都在一个平面上(minZ=200),他们应该在一个曲面上'''
    '''    取XZ平面上face landmark的三个极点,画一个圆'''
    '''    除了face landmark以外的所有点 的 z,都落到圆上'''
    '''5.1.1 face landmark上XZ平面的三个极点'''
    faceLandmarkOnXZ = []
    for faceLandmarkVline in faceLandmarkVlines:
        v, x, y, z, r, g, b = faceLandmarkVline.split()
        faceLandmarkOnXZ.append((float(x), float(z)))
    faceLandmarkOnXZMinX = min(faceLandmarkOnXZ, key=lambda x: x[0])
    faceLandmarkOnXZMaxX = max(faceLandmarkOnXZ, key=lambda x: x[0])
    faceLandmarkOnXZMaxZ = max(faceLandmarkOnXZ, key=lambda x: x[1])

    '''5.1.2 三点构成一个圆'''
    circleCenterXOnXZ, circleCenterZOnXZ, radiusOnXZ = threePoints2Circle(
        faceLandmarkOnXZMinX, faceLandmarkOnXZMaxX, faceLandmarkOnXZMaxZ)
    circleCenterZOnXZ = circleCenterZOnXZ-70
    '''5.1.3 把这个圆扩大,圆心不动,半径扩大至hair points的极点'''
    k1 = abs(circleCenterXOnXZ-max(originHairPoints, key=lambda x: x[0])[0])
    k2 = abs(circleCenterXOnXZ-min(originHairPoints, key=lambda x: x[0])[0])
    radiusOnXZ = max([k1, k2])+5
    rr, cc = circle_perimeter(int(circleCenterXOnXZ), int(
        circleCenterZOnXZ), int(radiusOnXZ))
    circleOnXZ = np.dstack([rr, cc])[0]
    '''5.1.4 hair points 的 z 落在圆上'''
    hairPointsVlines = []
    for (x, y) in originHairPoints:
        maxZ = 0
        for (x0, z0) in circleOnXZ:
            if int(x) == int(x0):
                if z0 > maxZ:
                    maxZ = z0
        hairVline = '{} {} {} {} {} {} {}'.format('v', x, y, maxZ, 0, 0, 0)
        hairPointsVlines.append(hairVline)
        maxZ = 0

    assert len(hairPointsVlines) == len(originHairPoints)

    '''6. HR: face landmarks + hair points'''
    originVlines = faceLandmarkVlines+hairPointsVlines

    '''7. HR: turn face and hair'''
    turnAngle = 10
    turnDirection = ['left', 'right']
    turnCenterMode = 'maxY'
    leftTurnVLines = turnHR(originVlines, turnAngle,
                            turnDirection[0], turnCenterMode)
    rightTurnVLines = turnHR(originVlines, turnAngle,
                             turnDirection[1], turnCenterMode)

    assert len(originVlines) == len(leftTurnVLines) == len(rightTurnVLines)

    '''8. HR: turn 3D --> 2D'''
    originPointsHR = []
    leftTurnPointsHR = []
    rightTurnPointsHR = []
    for originVline, leftTurnVLine, rightTurnVLine in zip(originVlines, leftTurnVLines, rightTurnVLines):
        _, x, y, _, _, _, _ = originVline.split()
        originPointsHR.append((float(x), float(y)))
        _, x, y, _, _, _, _ = leftTurnVLine.split()
        leftTurnPointsHR.append((float(x), float(y)))
        _, x, y, _, _, _, _ = rightTurnVLine.split()
        rightTurnPointsHR.append((float(x), float(y)))

    assert len(originPointsHR) == len(
        leftTurnPointsHR) == len(rightTurnPointsHR)

    # drawPointsOnImg(originPointsHR, imgHR, 'g')
    # drawPointsOnImg(turnPointsHR, imgHR, 'r')

    ''''9. inner ellipse'''
    left = min(originPointsHR, key=lambda x: x[0])[0]
    right = max(originPointsHR, key=lambda x: x[0])[0]
    up = min(originPointsHR, key=lambda x: x[1])[1]
    bottom = max(originPointsHR, key=lambda x: x[1])[1]
    innerEllipseCenterX = int((left+right)/2.0)
    innerEllipseCenterY = int((up+bottom)/2.0)
    innerEllipseSemiX = int((right-left)/2.0)
    innerEllipseSemiY = int((bottom-up)/2.0)
    rr, cc = ellipse_perimeter(innerEllipseCenterX, innerEllipseCenterY,
                               innerEllipseSemiY, innerEllipseSemiX, orientation=np.pi*1.5)
    innerEllipseVerts = np.dstack([rr, cc])[0]

    '''10. outer ellipse'''
    '''10.1 ratio = outer ellipse / inner ellipse'''
    '''     椭圆心和衣领的线段  和  椭圆的交点'''
    minDistance = np.inf
    for pt in innerEllipseVerts:
        distance = twoPointsDistance(pt, collarPoint)
        if distance < minDistance:
            minDistance = distance
            ratio = twoPointsDistance((innerEllipseCenterX, innerEllipseCenterY), collarPoint) / \
                twoPointsDistance(
                    (innerEllipseCenterX, innerEllipseCenterY), pt)
    '''10.2 outer ellipse'''
    outerEllipseSemiX = int(ratio*innerEllipseSemiX)
    outerEllipseSemiY = int(ratio*innerEllipseSemiY)
    rr, cc = ellipse_perimeter(innerEllipseCenterX, innerEllipseCenterY,
                               outerEllipseSemiY, outerEllipseSemiX, orientation=np.pi*1.5)
    outerEllipseVerts = np.dstack([rr, cc])[0]
    # drawPointsOnImg(outerEllipseVerts, imgHR, 'g')

    '''11. edge points on outer ellipse'''
    edgePoints = edgePointsOnOuterEllipse(outerEllipseVerts)

    '''12. final origin and turn points'''
    originPointsHRFinal = originPointsHR+edgePoints
    leftTurnPointsHRFinal = leftTurnPointsHR+edgePoints
    rightTurnPointsHRFinal = rightTurnPointsHR+edgePoints

    '''13. tri.txt'''
    triList = generateTriList(
        originPointsHRFinal, imgHR, triTxtPath='./turnTri.txt')

    '''14. warp'''
    # imgMorph = morph_modify_for_2D3D2D_low_resolution(
    #     originPointsHRFinal, turnPointsHRFinal, imgHR, triList)
    # imshow('imgMorph', imgMorph)
    # cv2.imwrite('./imgMorph.png', imgMorph)

    return originPointsHRFinal, leftTurnPointsHRFinal, rightTurnPointsHRFinal, triList