def test_coord_raises(): img = rgb2gray(data.astronaut()) s = np.linspace(0, 2 * np.pi, 400) x = 100 + 100 * np.sin(s) y = 220 + 100 * np.cos(s) init = np.array([x, y]).T # coordinates='xy' is not valid with pytest.raises(ValueError): active_contour(gaussian(img, 3), init, boundary_condition='periodic', alpha=0.015, beta=10, w_line=0, w_edge=1, gamma=0.001, max_num_iter=100, coordinates='xy') # coordinates=None is not valid with pytest.raises(ValueError): active_contour(gaussian(img, 3), init, boundary_condition='periodic', alpha=0.015, beta=10, w_line=0, w_edge=1, gamma=0.001, max_num_iter=100, coordinates=None)
def test_RGB(): img = gaussian(data.text(), 1) imgR = np.zeros((img.shape[0], img.shape[1], 3)) imgG = np.zeros((img.shape[0], img.shape[1], 3)) imgRGB = np.zeros((img.shape[0], img.shape[1], 3)) imgR[:, :, 0] = img imgG[:, :, 1] = img imgRGB[:, :, :] = img[:, :, None] x = np.linspace(5, 424, 100) y = np.linspace(136, 50, 100) init = np.array([x, y]).T snake = active_contour(imgR, init, bc='fixed', alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1) refx = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42] refy = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125] assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx) assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy) snake = active_contour(imgG, init, bc='fixed', alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1) assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx) assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy) snake = active_contour(imgRGB, init, bc='fixed', alpha=0.1, beta=1.0, w_line=-5/3., w_edge=0, gamma=0.1) assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx) assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_bad_input(): img = np.zeros((10, 10)) x = np.linspace(5, 424, 100) y = np.linspace(136, 50, 100) init = np.array([x, y]).T with testing.raises(ValueError): active_contour(img, init, bc='wrong') with testing.raises(ValueError): active_contour(img, init, max_iterations=-15)
def test_bad_input(): img = np.zeros((10, 10)) r = np.linspace(136, 50, 100) c = np.linspace(5, 424, 100) init = np.array([r, c]).T with pytest.raises(ValueError): active_contour(img, init, boundary_condition='wrong') with pytest.raises(ValueError): active_contour(img, init, max_num_iter=-15) with expected_warnings(["`max_iterations` is a deprecated argument"]): snake = active_contour(img, init, max_iterations=15)
def segment_0(path): #image = data.binary_blobs() image = data.load(path) gray=image[:,:,0] val = filters.threshold_local(gray,block_size=131) val = gray > val #mask = gray < val #image_show(gray) image_show(val) return seg.active_contour(gray) #segmented = image > (value concluded from histogram i.e 50, 70, 120) text_threshold = filters.threshold_local(gray,block_size=51, offset=10) # Hit tab with the cursor after the underscore to get all the methods. image_show(gray < text_threshold);
def save_contours(img_name, gamma): img = give_me_the_original('birdog.jpg') img = rgb2gray(img) s = np.linspace(0, 2 * np.pi, 200) x = 310 + 70 * np.cos(s) y = 230 + 70 * np.sin(s) init = np.array([x, y]).T snake = active_contour(gaussian(img, 3), init, alpha=0.015, beta=10, gamma=float(gamma)) fig, ax = plt.subplots(figsize=(7, 7)) ax.imshow(img, cmap=plt.cm.gray) ax.plot(init[:, 0], init[:, 1], '--r', lw=3) ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3) ax.set_xticks([]), ax.set_yticks([]) ax.axis([0, img.shape[1], img.shape[0], 0]) figpath = 'img/edits/' figname = f"{img_name}_gamma-{str(gamma)[0:6].replace('.',',')}.jpg" plt.savefig(figpath + figname) print(f"Saved {figname}") return
def get_snake(img): # 中值滤波 # dst = cv2.medianBlur(img ,13) # 锐化 # dst = cv_filter2d(dst) # canny提取轮廓 # dst = cv2.Canny(dst, 100, 200) dst = img x_0, y_0 = find_c(dst) t = np.linspace(0, 2 * np.pi, 500) # 参数t, [0,2π] x = x_0 + 195 * np.cos(t) y = y_0 + 195 * np.sin(t) # 构造初始Snake init = np.array([x, y]).T # shape=(400, 2) # Snake模型迭代输出 snake = active_contour(gaussian(dst, 3), snake=init, alpha=1.1, beta=2.0, gamma=0.01, w_line=0, w_edge=10) plt.figure(figsize=(5, 5)) plt.imshow(dst, cmap="gray") plt.plot(snake[:, 0], snake[:, 1], '-w', lw=3) plt.xticks([]), plt.yticks([]), plt.axis("off") plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0) plt.margins(0, 0) plt.savefig(out_dir + str(10) + '.jpg') plt.show() return snake
def snakes_localization(grayscale_image, start_pnt, radius): s = np.linspace(0, 2 * np.pi, 400) x = start_pnt[0] + radius * np.cos(s) y = start_pnt[1] + radius * np.sin(s) init = np.array([x, y]).T snake = active_contour(skimage.filters.gaussian(grayscale_image, 3), init, bc='periodic', alpha=0.01, beta=10, gamma=0.1, w_line=0, w_edge=-10) cv2.imwrite('hist_equal.png', exposure.equalize_adapthist(grayscale_image)) img = grayscale_image #cv2.cvtColor(grayscale_image, cv2.COLOR_GRAY2BGR) cv2.circle(img, (start_pnt[1], start_pnt[0]), radius, color=(0, 255, 0), thickness=3) print "Snake size: {}".format(len(snake)) for i in range(0, len(snake)): cv2.circle(img, (int(snake[i][1]), int(snake[i][0])), 1, color=(0, 0, 255), thickness=1) cv2.imshow("snakes", img) print 'Snakes localization is finished'
def snake_skimage(): # to mitigate the problem of holes in building footprints, we could use # snake. We initialise the snale wioth the contour of axis, then # make the snake balloon # the idea is to work on small street segment one by one # we couls also use a more sophisticated method to compute # all snake at the same time, for instance from PIL import Image import numpy as np import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage import data from skimage.filters import gaussian from skimage.segmentation import active_contour from skimage import measure from skimage.transform import rotate rotated_image = rotate(axis, 180, resize=True) plt.imshow(rotated_image) np.max(axis); np.min(axis) contours = measure.find_contours(axis*1.0, 0) fig, ax = plt.subplots() ax.imshow(jac, interpolation='nearest', cmap=plt.cm.gray) for n, contour in enumerate(contours): contour[:,[0, 1]] = contour[:,[1, 0]] ax.plot(contour[:, 0], contour[:, 1], linewidth=2) print(n,contour[0,:] ) for n, contour in enumerate(contours): print(n, len(contour)) test_contour = contours[88] snake = active_contour(jac, test_contour , alpha= -1 , beta=10 , gamma=0.001 , max_iterations=50 , bc='periodic' , w_line = -1) fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111) plt.gray() ax.imshow(jac) ax.plot(test_contour[:, 0], test_contour[:, 1], '--r', lw=3) #for n, contour in enumerate(contours): # ax.plot(contours[n][:, 1], contours[n][:, 0], '--r', lw=3) ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3) ax.set_xticks([]), ax.set_yticks([]) ax.axis([0, jac.shape[0], jac.shape[1], 0])
def test_end_points(): img = data.astronaut() img = rgb2gray(img) s = np.linspace(0, 2*np.pi, 400) x = 220 + 100*np.cos(s) y = 100 + 100*np.sin(s) init = np.array([x, y]).T snake = active_contour(gaussian(img, 3), init, bc='periodic', alpha=0.015, beta=10, w_line=0, w_edge=1, gamma=0.001, max_iterations=100) assert np.sum(np.abs(snake[0, :]-snake[-1, :])) < 2 snake = active_contour(gaussian(img, 3), init, bc='free', alpha=0.015, beta=10, w_line=0, w_edge=1, gamma=0.001, max_iterations=100) assert np.sum(np.abs(snake[0, :]-snake[-1, :])) > 2 snake = active_contour(gaussian(img, 3), init, bc='fixed', alpha=0.015, beta=10, w_line=0, w_edge=1, gamma=0.001, max_iterations=100) assert_allclose(snake[0, :], [x[0], y[0]], atol=1e-5)
def test_free_reference(): img = data.text() x = np.linspace(5, 424, 100) y = np.linspace(70, 40, 100) init = np.array([x, y]).T snake = active_contour(gaussian(img, 3), init, bc='free', alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1) refx = [10, 13, 16, 19, 23, 26, 29, 32, 36, 39] refy = [76, 76, 75, 74, 73, 72, 71, 70, 69, 69] assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx) assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_fixed_reference(): img = data.text() x = np.linspace(5, 424, 100) y = np.linspace(136, 50, 100) init = np.array([x, y]).T snake = active_contour(gaussian(img, 1), init, bc='fixed', alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1) refx = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42] refy = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125] assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx) assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_periodic_reference(): img = data.astronaut() img = rgb2gray(img) s = np.linspace(0, 2*np.pi, 400) x = 220 + 100*np.cos(s) y = 100 + 100*np.sin(s) init = np.array([x, y]).T snake = active_contour(gaussian(img, 3), init, alpha=0.015, beta=10, w_line=0, w_edge=1, gamma=0.001) refx = [299, 298, 298, 298, 298, 297, 297, 296, 296, 295] refy = [98, 99, 100, 101, 102, 103, 104, 105, 106, 108] assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx) assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def snake(img,origin=[0.0,0.0],r=0.3): s = np.linspace(0, 2*np.pi, 50) x = origin[0] + r*np.cos(s) y = origin[1] + r*np.sin(s) init = np.array([x, y]).T # snake = active_contour(gaussian(img, 1), # init, alpha=10.0, beta=100.0, gamma=0.01) snake = active_contour(gaussian(img, 1),init) return snake
def snake_fit(image,initial,w_line=5,w_edge=0,max_px_move=1,beta=1,gamma=0.1): to_fit = image min_x,max_x = np.min(initial[:,0]),np.max(initial[:,0]) min_y,max_y = np.min(initial[:,1]),np.max(initial[:,1]) fudge_x = int(np.ceil((max_x-min_x) * 0.1)) fudge_y = int(np.ceil((max_y-min_y) * 0.1)) lower_x = 0#max(0,min_x-fudge_x) lower_y = 0#max(0,min_y-fudge_y) #to_fit = to_fit[lower_x:max_x+fudge_x, # lower_y:max_y+fudge_y] initial_x_shifted = initial[:,0]-lower_x initial_y_shifted = initial[:,1]-lower_y initial = np.array((initial_x_shifted,initial_y_shifted)).T min_image,max_image = np.min(to_fit),np.max(to_fit) to_fit = ((to_fit - min_image)/(max_image - min_image)) * 256 to_fit = to_fit.astype(np.uint8) initial_snake = initial.astype(np.float64) snake = active_contour(to_fit,convergence=1e-3,max_iterations=5e3, snake=initial_snake,w_line=w_line, w_edge=w_edge,beta=beta,gamma=gamma, bc='fixed',max_px_move=max_px_move) snake[:,0] += lower_x snake[:,1] += lower_y return snake
arg_parser.add_argument('--gamma', type=float, default=0.001, help='gamma value, explicit time stepping') arg_parser.add_argument('--n', type=int, default=360, help='number of points in snake') arg_parser.add_argument('--no-snake', action='store_true', help='do not compute snake, only show initial ' 'contour') options = arg_parser.parse_args() image = rgb2gray(data.astronaut()) smoothed_image = gaussian(image, 3) x0, y0, radius = 220, 100, 100 theta = np.linspace(0, 2*np.pi, options.n) x = x0 + radius*np.cos(theta) y = y0 + radius*np.sin(theta) initial_snake = np.array([x, y]).T if not options.no_snake: snake = active_contour(smoothed_image, initial_snake, alpha=options.alpha, beta=options.beta, gamma=options.gamma) figure = plt.figure(figsize=(7, 7)) axis = figure.add_subplot(111) plt.gray() axis.imshow(image) axis.plot(initial_snake[:, 0], initial_snake[:, 1], '--b') if not options.no_snake: axis.plot(snake[:, 0], snake[:, 1], '-r', lw=1.5) axis.axis([0, image.shape[1], image.shape[0], 0]) plt.show()
img = data.astronaut() img = rgb2gray(img) s = np.linspace(0, 2*np.pi, 400) x = 220 + 100*np.cos(s) y = 100 + 100*np.sin(s) init = np.array([x, y]).T if not new_scipy: print('You are using an old version of scipy. ' 'Active contours is implemented for scipy versions ' '0.14.0 and above.') if new_scipy: snake = active_contour(gaussian(img, 3), init, alpha=0.015, beta=10, gamma=0.001) fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111) plt.gray() ax.imshow(img) ax.plot(init[:, 0], init[:, 1], '--r', lw=3) ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3) ax.set_xticks([]), ax.set_yticks([]) ax.axis([0, img.shape[1], img.shape[0], 0]) ###################################################################### # Here we initialize a straight line between two points, `(5, 136)` and # `(424, 50)`, and require that the spline has its end points there by giving # the boundary condition `bc='fixed'`. We furthermore make the algorithm # search for dark lines by giving a negative `w_line` value.
# -*- coding: utf-8 -*- # @Author: bxsh # @Email: [email protected] # @File: test.py # @Date: 2017/8/24 13:53 import cv2 import numpy as np from skimage.draw import circle_perimeter from skimage.segmentation import active_contour from skimage.filters import gaussian if __name__ == '__main__': # a = np.uint8(np.zeros([300, 300])) # a[50:-50, 50:-50] = 1 # a[149:-149, 149:-149] = 0 # b = cv2.erode(a, kernel=(3, 3), iterations=5) # cv2.imshow('a', a * 255) # cv2.imshow('b', b * 255) # cv2.waitKey() img = np.zeros((100, 100)) rr, cc = circle_perimeter(35, 45, 25) img[rr, cc] = 1 img = gaussian(img, 2) s = np.linspace(0, 2 * np.pi, 100) init = 50 * np.array([np.cos(s), np.sin(s)]).T + 50 snake = active_contour(img, init, w_edge=0, w_line=1) print(snake.shape) pass
sp = utility.readVTKSP('/home/marsdenlab/projects/OBG_full/raw/{}.truth.mag.vts'.format(f)) contour = utility.VTKPDReadAndReorder('/home/marsdenlab/projects/OBG_full/raw/{}.truth.ls.vtp'.format(f)) mag = utility.VTKSPtoNumpyFromFile('/home/marsdenlab/projects/OBG_full/raw/{}.truth.mag.vts'.format(f)) spacing = sp.GetSpacing() origin = sp.GetOrigin() bounds = [origin[0], origin[0]+ 64*spacing[0], origin[1], origin[1]+64*spacing[1]] seg = utility.contourToSeg(contour,origin,[64,64],spacing) H,W = seg.shape contour_pred = utility.segToContour(seg, origin, spacing, 0.55)[0] ps = np.linspace(0,2*np.pi-0.1,50) init_snake = 0.3*np.asarray([np.sin(ps),np.cos(ps)]) init_snake = init_snake.T snake_contour = segmentation.active_contour(seg, init_snake, w_edge=100) fig = util_plot.Figure(1,1, height=500,width=500) fig.add_heatmap(seg, bounds) fig.add_scatter2d(contour[:,0],contour[:,1], legend='contour') fig.add_scatter2d(contour_pred[:,0],contour_pred[:,1], legend='contour_pred') fig.add_scatter2d(init_snake[:,0],init_snake[:,1], legend='snake init') fig.add_scatter2d(snake_contour[:,0],snake_contour[:,1], legend='contour_snake') fig.plot('./plots/plot1.html') fig2 = util_plot.Figure(1,1, height=500,width=500) fig2.add_heatmap(mag[0], bounds) fig2.add_scatter2d(contour[:,1],contour[:,0], legend='contour') fig2.plot('./plots/plot2.html') #test OBG stuff