def test_performance(): def for_loop_efd(contour, order=10, normalize=False): """Calculate elliptical Fourier descriptors for a contour. :param numpy.ndarray contour: A contour array of size ``[M x 2]``. :param int order: The order of Fourier coefficients to calculate. :param bool normalize: If the coefficients should be normalized; see references for details. :return: A ``[order x 4]`` array of Fourier coefficients. :rtype: :py:class:`numpy.ndarray` """ dxy = np.diff(contour, axis=0) dt = np.sqrt((dxy**2).sum(axis=1)) t = np.concatenate([([0.]), np.cumsum(dt)]) T = t[-1] phi = (2 * np.pi * t) / T coeffs = np.zeros((order, 4)) for n in range(1, order + 1): const = T / (2 * n * n * np.pi * np.pi) phi_n = phi * n d_cos_phi_n = np.cos(phi_n[1:]) - np.cos(phi_n[:-1]) d_sin_phi_n = np.sin(phi_n[1:]) - np.sin(phi_n[:-1]) a_n = const * np.sum((dxy[:, 0] / dt) * d_cos_phi_n) b_n = const * np.sum((dxy[:, 0] / dt) * d_sin_phi_n) c_n = const * np.sum((dxy[:, 1] / dt) * d_cos_phi_n) d_n = const * np.sum((dxy[:, 1] / dt) * d_sin_phi_n) coeffs[n - 1, :] = a_n, b_n, c_n, d_n sample_size = 100 start = time.time() for _ in range(sample_size): pyefd.elliptic_fourier_descriptors(contour_1, order=30) stop = time.time() vectorized_time = stop - start print( "Time taken to create order 30 efd coefficients for 1000 contours:", vectorized_time, ) start = time.time() for _ in range(sample_size): for_loop_efd(contour_1, order=30) stop = time.time() for_loop_time = stop - start print( "Time taken to create order 30 efd coefficients for 100 contours:", for_loop_time, ) assert vectorized_time < for_loop_time
def predict(self,card): model_file = 'model.pkl' try: xs,y = np.loadtxt(card+".txt", unpack=True) except Exception: tkMessageBox.showinfo("ERROR!","Error! Card you Entered is not Exist \n Please check file name") contour=[] i=0 for x in xs: contour.append([x,y[i]]) i=i+1 coeffs = pyefd.elliptic_fourier_descriptors(contour, order=15,normalize=True) pyefd.plot_efd(coeffs) coeffs = coeffs.flatten()[1:] # load model net = pickle.load( open( model_file, 'rb' )) # predict p = net.activate(coeffs) #draw x = [1,2,3] LABELS = ["Normal", "Gas Interference", "Fluid Pound"] plt.bar(x, p, align='center') plt.xticks(x, LABELS) plt.show() ########## np.savetxt('predictions.txt', p, fmt = '%.6f' )
def FourierDescriptor(image): #image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) #ret2,image = cv2.threshold(image,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #find the contours of the object #in the image cvtimage = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) #find the contour points of the image image_contours = SCDescriptor.get_points_from_img(cvtimage) #find the centroid of the contour centroid, _ = find_minEnclosingCircle(cvtimage) #Compute the descriptor start_time = time.process_time() #find the distances between the centroid and all the contour points #to make the descriptor translation invariant dist_c = [] for con_point in image_contours: radius = dist.euclidean(centroid, tuple(con_point)) theta = math.atan2(con_point[1] - centroid[1], con_point[0] - centroid[0]) dist_c.append((radius, theta)) dist_c = np.asarray(dist_c) dist_c = np.transpose(dist_c) descriptor = elliptic_fourier_descriptors(dist_c, order=10) end_time = time.process_time() compute_time = end_time - start_time #The output of the descriptor function does not #create a feature vector, so we have to modify the output #return descriptor.flatten()[3:], compute_time return descriptor.flatten(), compute_time
def predict(self, card): model_file = 'model.pkl' try: xs, y = np.loadtxt(card + ".txt", unpack=True) except Exception: tkMessageBox.showinfo( "ERROR!", "Error! Card you Entered is not Exist \n Please check file name" ) contour = [] i = 0 for x in xs: contour.append([x, y[i]]) i = i + 1 coeffs = pyefd.elliptic_fourier_descriptors(contour, order=15, normalize=True) pyefd.plot_efd(coeffs) coeffs = coeffs.flatten()[1:] # load model net = pickle.load(open(model_file, 'rb')) # predict p = net.activate(coeffs) #draw x = [1, 2, 3] LABELS = ["Normal", "Gas Interference", "Fluid Pound"] plt.bar(x, p, align='center') plt.xticks(x, LABELS) plt.show() ########## np.savetxt('predictions.txt', p, fmt='%.6f')
def extract_efd_features(image, n=10): contours = get_contours(image) if len(contours) == 0: return np.zeros((4 * n))[3:] efd = elliptic_fourier_descriptors(contours[0], order=n, normalize=True) return efd.flatten()[3:]
def extract_efd_features(image, n=10): contours = get_contours(image) if len(contours) == 0: return np.zeros((4*n))[3:] efd = elliptic_fourier_descriptors(contours[0], order=n, normalize=True) return efd.flatten()[3:]
def test_larger_contour(): locus = pyefd.calculate_dc_coefficients(contour_1) coeffs = pyefd.elliptic_fourier_descriptors(contour_1, order=50) number_of_points = contour_1.shape[0] reconstruction = pyefd.reconstruct_contour(coeffs, locus, number_of_points) hausdorff_distance, _, _ = directed_hausdorff(contour_1, reconstruction) assert hausdorff_distance < 0.4
def plot_smooth_contour(cont_stat, cont_thres, n_point): conf = smooth_grid(cont_stat, n_point) < smooth_grid(cont_thres, n_point) conf = expand_image(conf) contours = [x - 10 for x in measure.find_contours(conf, 0.9)] for contour in contours: coeffs = elliptic_fourier_descriptors(contour, order=10) xt, yt = efd_curve(coeffs, np.mean(contour, axis=0)) plt.plot(yt, xt) plt.xlim(0, n_point - 1) plt.ylim(0, n_point - 1)
def test_normalizing_3(): #rotate and scale contour_1 by a known amount theta = np.radians(30) c, s = np.cos(theta), np.sin(theta) R = np.array(((c, -s), (s, c))) * 1.5 contour_2 = np.transpose(np.dot(R, np.transpose(contour_1))) c1, t1 = pyefd.elliptic_fourier_descriptors(contour_1, normalize=True, return_transformation=True) c2, t2 = pyefd.elliptic_fourier_descriptors(contour_2, normalize=True, return_transformation=True) #check if coefficients are equal (invariance) np.testing.assert_almost_equal(c1, c2, decimal=12) #check if normalization parametres match the initial transform np.testing.assert_almost_equal(t1[0] * 1.5, t2[0], decimal=12) np.testing.assert_almost_equal((t1[1] + np.radians(30)) % (2 * pi), t2[1], decimal=12)
def EllipticFourier(): print("EF\n") path_EF = "C:\Data\Feature-Extraction" if not os.path.exists(path_EF): os.makedirs(path_EF) file = open("C:\Data\Feature-Extraction\Elliptic-Fourier.txt", "w") # file = open(r"C:\Users\Ever\Desktop\Elliptic-Fourier.txt", "w") lstFiles = [] # nombre de imagenes path = r"C:\Data\Image-Segmentation" for (path, _, archivos) in walk(path): for arch in archivos: (nomArch, ext) = os.path.splitext(arch) if (ext == ".JPG"): lstFiles.append(nomArch + ext) direc = path + "\\" + nomArch + ext name = nomArch + ext print(nomArch + ext) img_binary = cv2.imread(direc) img_binary = cv2.cvtColor(img_binary, cv2.COLOR_BGR2GRAY) ret, img_binary = cv2.threshold(img_binary, 127, 255, 0) _, contours, hierarchy = cv2.findContours( img_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) maxcontour = max(contours, key=cv2.contourArea) coeffs = [] # Find the coefficients of all contours coeffs.append( elliptic_fourier_descriptors(np.squeeze(maxcontour), order=13)) # print("coeff",coeffs) coeffs2 = [] for row in coeffs: for elem in row: coeffs2.append(elem) coeffs = [] for row in coeffs2: for elem in row: coeffs.append(elem) file.write(name) for item in range(len(coeffs)): file.write(",%.4f" % coeffs[item]) file.write("," + name[0] + "\n") file.close()
def create_contour(mask): """Turn as mask into a contour polygon. The polygon is smoothed via Fourier descriptors Parameters ---------- mask : 2D numpy array mask of a region Returns ------- recon : Nx2 numpy array coordinates of contour """ # extract contour by recovering contour of filled mask reg = skimage.measure.regionprops_table( skimage.morphology.label(mask), properties=( "label", "area", "filled_area", "eccentricity", "extent", "filled_image", "coords", "bbox", ), ) regp = pd.DataFrame(reg).sort_values(by="filled_area", ascending=False) new_mask2 = np.zeros(mask.shape) new_mask2[regp.iloc[0]["bbox-0"]:regp.iloc[0]["bbox-2"], regp.iloc[0]["bbox-1"]:regp. iloc[0]["bbox-3"], ] = regp.iloc[0].filled_image area = regp.iloc[0].filled_area contour = skimage.measure.find_contours(new_mask2, 0.8) sel_contour = contour[np.argmax([len(x) for x in contour])] # calculate a smoothed verions using a reconstruction via Fourier descriptors coeffs = elliptic_fourier_descriptors(sel_contour, order=100, normalize=False) coef0 = calculate_dc_coefficients(sel_contour) recon = reconstruct_contour(coeffs, locus=coef0, num_points=1500) return recon, area
def test_fit_1(): n = 300 locus = pyefd.calculate_dc_coefficients(contour_1) coeffs = pyefd.elliptic_fourier_descriptors(contour_1, order=20) t = np.linspace(0, 1.0, n) xt = np.ones((n,)) * locus[0] yt = np.ones((n,)) * locus[1] for n in pyefd._range(coeffs.shape[0]): xt += (coeffs[n, 0] * np.cos(2 * (n + 1) * np.pi * t)) + \ (coeffs[n, 1] * np.sin(2 * (n + 1) * np.pi * t)) yt += (coeffs[n, 2] * np.cos(2 * (n + 1) * np.pi * t)) + \ (coeffs[n, 3] * np.sin(2 * (n + 1) * np.pi * t)) assert True
def test_fit_1(): n = 300 locus = pyefd.calculate_dc_coefficients(contour_1) coeffs = pyefd.elliptic_fourier_descriptors(contour_1, order=20) t = np.linspace(0, 1.0, n) xt = np.ones((n, )) * locus[0] yt = np.ones((n, )) * locus[1] for n in pyefd._range(coeffs.shape[0]): xt += (coeffs[n, 0] * np.cos(2 * (n + 1) * np.pi * t)) + \ (coeffs[n, 1] * np.sin(2 * (n + 1) * np.pi * t)) yt += (coeffs[n, 2] * np.cos(2 * (n + 1) * np.pi * t)) + \ (coeffs[n, 3] * np.sin(2 * (n + 1) * np.pi * t)) assert True
def test_reconstruct_simple_contour(): simple_polygon = np.array([[1., 1.], [0., 1.], [0., 0.], [1., 0.], [1., 1.]]) number_of_points = simple_polygon.shape[0] locus = pyefd.calculate_dc_coefficients(simple_polygon) coeffs = pyefd.elliptic_fourier_descriptors(simple_polygon, order=30) reconstruction = pyefd.reconstruct_contour(coeffs, locus, number_of_points) # with only 2 decimal accuracy it is a bit of a course test, but it will do # directly comparing the two polygons will only work here, because efd coefficients will be cycle-consistent np.testing.assert_array_almost_equal(simple_polygon, reconstruction, decimal=2) hausdorff_distance, _, _ = directed_hausdorff(reconstruction, simple_polygon) assert hausdorff_distance < 0.01
def plot_smooth_contour(conf, hierarchy='NH', **kwargs): """ Plot 2d contour after Fourier smoothing. """ n_point = conf.shape[0] conf = expand_image(conf) contours = [x - 10 for x in measure.find_contours(conf, 0.9)] contour = contours[0] coeffs = elliptic_fourier_descriptors(contour, order=10) xt, yt = efd_curve(coeffs, np.mean(contour, axis=0)) if hierarchy == 'NH': colour = 'dodgerblue' elif hierarchy == 'IH': colour = 'firebrick' plt.plot(yt, xt, c=colour, **kwargs) plt.xlim(0, n_point - 1) plt.ylim(0, n_point - 1)
def add_efd(self): coeffs = [] for i in range(len(self.s)): try: _, contours, hierarchy = cv2.findContours( self.s[i][0].astype(np.uint8), 1, 2) if not len(contours): coeffs.append(0) continue cnt = contours[0] if len(cnt) >= 5: contour = [] for i in range(len(contours[0])): contour.append(contours[0][i][0]) coeffs.append( elliptic_fourier_descriptors(contour, order=10, normalize=False)) else: coeffs.append(0) except AttributeError: coeffs.append(0) self.r = coeffs
def test_efd_shape_1(): coeffs = pyefd.elliptic_fourier_descriptors(contour_1, order=10) assert coeffs.shape == (10, 4)
def test_normalizing_1(): c = pyefd.elliptic_fourier_descriptors(contour_1, normalize=False) assert np.abs(c[0, 0]) > 0.0 assert np.abs(c[0, 1]) > 0.0 assert np.abs(c[0, 2]) > 0.0
"""Elliptic Fourier Descriptors parametrizing a closed countour (in red)""" import vedo, pyefd shapes = vedo.load(vedo.dataurl+'timecourse1d.npy') sh = shapes[55] sr = vedo.Line(sh).mirror('x').reverse() sm = vedo.merge(sh, sr).c('red5').lw(3) pts = sm.points()[:,(0,1)] rlines = [] for order in range(5,30, 5): coeffs = pyefd.elliptic_fourier_descriptors(pts, order=order, normalize=False) a0, c0 = pyefd.calculate_dc_coefficients(pts) rpts = pyefd.reconstruct_contour(coeffs, locus=(a0,c0), num_points=400) color = vedo.colorMap(order, "Blues", 5,30) rline = vedo.Line(rpts).lw(3).c(color) rlines.append(rline) sm.z(0.1) # move it on top so it's visible vedo.show(sm, *rlines, __doc__, axes=1, bg='k', size=(1190, 630), zoom=1.8)
dataset_config = LENIADataset.default_config() dataset_config.data_root = '/gpfswork/rech/zaj/ucf28eq/data/lenia_datasets/data_005/' dataset_config.split = 'train' dataset = LENIADataset(config=dataset_config) animal_ids = torch.where(dataset.labels == 0)[0].numpy() # create fourier descriptors and save statistics normalized_coefficients = np.zeros((dataset.n_images, n_harmonics, 4)) errors = np.zeros(dataset.n_images) for idx in range(dataset.n_images): im = dataset.get_image(idx).squeeze().numpy() contour = get_contour(im, threshold=threshold) if contour is not None: # elliptical Fourier descriptor's coefficients. coeffs = pyefd.elliptic_fourier_descriptors(contour, order=n_harmonics) # normalize coeffs normalized_coeffs, L = pyefd.normalize_efd(deepcopy(coeffs)) # recon_contour if len(contour) > 0: locus = pyefd.calculate_dc_coefficients(contour) else: locus = (0, 0) recon_contour = pyefd.reconstruct_contour(coeffs, locus=locus, num_points=300) # error measure error = calc_contours_distance(contour, recon_contour) / (2 * L) * 100 normalized_coefficients[idx] = normalized_coeffs errors[idx] = error
def test_normalizing_2(): c = pyefd.elliptic_fourier_descriptors(contour_1, normalize=True) np.testing.assert_almost_equal(c[0, 0], 1.0, decimal=14) np.testing.assert_almost_equal(c[0, 1], 0.0, decimal=14) np.testing.assert_almost_equal(c[0, 2], 0.0, decimal=14)
yp = np.loadtxt("I:/Thesis - EFD/HittingUp,x3.txt", delimiter=',', usecols=(np.arange(101, 202)), unpack=True) i = 0 print(xp.shape) for value in xx.values: contour = [] ii = 0 for x in value: y = yy.values[i] contour.append([x, y[ii]]) ii = ii + 1 i = i + 1 coeffs = pyefd.elliptic_fourier_descriptors(contour, order=15, normalize=True) #pyefd.plot_efd(coeffs) coeffs = coeffs.flatten()[1:] save = open("input.dat", "a") np.savetxt(save, coeffs.reshape(1, coeffs.shape[0])) # save card diagnosis into output file save2 = open("output.dat", "a") output = np.zeros([1, 3], dtype=np.float32) if Diagnosis == 1: np.savetxt(save2, output.reshape(1, output.shape[1]), newline="\r") elif Diagnosis == 2: output[0, 0] = 1 np.savetxt(save2, output.reshape(1, output.shape[1]), newline="\r") elif Diagnosis == 3: output[0, 1] = 1
def test_efd(self): geom1 = 'POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))' geom1 = gv.vectorize_wkt(geom1) geom2 = 'POLYGON((1 1, 0 1, 0 0, 1 0, 1 1))' geom2 = gv.vectorize_wkt(geom2) coords_batch = geom2[:, :2] coords_batch = coords_batch.reshape(1, geom2.shape[0], 2) pyefd_descriptors = pyefd.elliptic_fourier_descriptors(coords_batch[0], order=10) numpy_vectorized_descriptors = numpy_vectorized_efd(coords_batch[0], order=10) polygon2_tensor = torch.from_numpy(coords_batch) polygon2_tensor.requires_grad = True pytorch_descriptors = efd(polygon2_tensor, order=10) with self.subTest('It does not accept a numpy ndarray'): with self.assertRaises(AssertionError): efd(geom1) with self.subTest('It rejects 3D geometries'): with self.assertRaises(AssertionError): efd(torch.rand((10, 3))) with self.subTest('Our stand-in efd function does the same as pyefd'): np.testing.assert_array_equal(pyefd_descriptors, numpy_vectorized_descriptors) with self.subTest('The pytorch efd does the same as the numpy vectorized function'): np.testing.assert_array_almost_equal(pytorch_descriptors[0].detach().numpy(), numpy_vectorized_descriptors) with self.subTest('It creates an elliptic fourier descriptor of a geometry, the same as pyefd creates'): # polygon1_tensor = geom1[:, :2] # polygon1_tensor = torch.from_numpy(polygon1_tensor) # polygon1_efd = efd(polygon1_tensor, order=10).numpy() np.testing.assert_array_almost_equal(pyefd_descriptors, pytorch_descriptors[0].detach().numpy()) with self.subTest('It handles inputs of zeros without nans'): zero_coordinates = torch.zeros((1, 10, 2), dtype=torch.double) coeffs = efd(zero_coordinates) coeffs = coeffs.detach().numpy() for element in coeffs.flatten(): self.assertFalse(np.isnan(element)) with self.subTest('It creates equal coefficients for replication-padded coordinate sequences'): torch.manual_seed(42) random_coordinates = torch.rand((1, 4, 2), dtype=torch.double) last_point = random_coordinates[:, -1] replication_padding = last_point.repeat(1, 4, 1) padded_random_coords = torch.cat((random_coordinates, replication_padding), dim=1) non_zero_coeffs = efd(random_coordinates).detach().numpy() padded_coeffs = efd(padded_random_coords).detach().numpy() np.testing.assert_array_almost_equal(non_zero_coeffs, padded_coeffs) with self.subTest('It creates descriptors for a batch of size 2 same as the pyefd implementation'): size_two_batch = torch.cat((polygon2_tensor, polygon2_tensor * 2), dim=0) resized_descriptors = pyefd.elliptic_fourier_descriptors(polygon2_tensor[0].detach().numpy() * 2, order=10) size_two_descriptors = efd(size_two_batch) size_two_descriptors = size_two_descriptors.detach().numpy() np.testing.assert_array_almost_equal(pyefd_descriptors, size_two_descriptors[0]) np.testing.assert_array_almost_equal(resized_descriptors, size_two_descriptors[1]) with self.subTest('It creates a differentiable function, returning gradients'): random_coordinates = torch.randn((1, 4, 2), dtype=torch.double, requires_grad=True) descriptors = efd(random_coordinates) scalar = torch.mean(descriptors) scalar.backward() gradients = random_coordinates.grad self.assertEqual(gradients.shape, random_coordinates.shape)
def coeffFourier(contorno): global nro_coef coeff = elliptic_fourier_descriptors(np.squeeze(contorno), order=nro_coeficientes) return coeff.flatten()[3:]
# diamond # rCos = np.array([0.5, 0.427, 0.0, 0.0732]) # zSin = np.array([0.0, 0.427, 0.0, -0.0732]) # D # rCos = np.array([3.0, 0.991, 0.136]) # zSin = np.array([0.0, 1.409, -0.118]) # belt # rCos = np.array([3.0, 0.453, 0.0, 0.0 ]) # zSin = np.array([0.0, 0.6 , 0.0, 0.196]) # ellipse # rCos = np.array([3.0, 1.0]) # zSin = np.array([0.0, 3.0]) # evaluate curve geometry given as Fourier coefficients above n = 300 contour = np.zeros([n,2]) theta = np.linspace(0.0, 2.0*np.pi, n) mMax = len(rCos) for m in range(mMax): contour[:,0] += rCos[m] * np.cos(m*theta) contour[:,1] += zSin[m] * np.sin(m*theta) # apply pyefd to get elliptic Fourier descriptors coeffs = pyefd.elliptic_fourier_descriptors(contour) a0, c0 = pyefd.calculate_dc_coefficients(contour) pyefd.plot_efd(coeffs, locus=(a0,c0), contour=contour)
def test_efd_shape_2(): c = pyefd.elliptic_fourier_descriptors(contour_1, order=40) assert c.shape == (40, 4)
def efd_feature(contour): coeffs = elliptic_fourier_descriptors(contour, order=10, normalize=True) return coeffs.flatten()[3:]
print("1.Normal Conditions\n2.Gas Interference\n3.Fluid Pound\n4.Traveling Valve Leak\n5.Standing Valve Leak\n6.Pump Hitting on Top\n7.Pump Hitting on Bottom\n8.Plugged Pump Intake\n9.Flumping\n10.Gas Lock\n11.Tubing Movement or Malfunctions in Tubing anchor\n12.Rod Parted\n13.Oil Too viscous") #Cards = input("Enter cards File Name : ") Diagnosis = input("Enter Downhole Diagnosis index :") # x,y values for cards i=1 while (os.path.isfile("I:\Thesis - EFD\leak_standing\ls"+str(i)+".txt") ): #get x,y and plot all cards x,y = np.loadtxt("I:\Thesis - EFD\leak_standing\ls"+str(i)+".txt", unpack=True) plt.plot(x, y) i=i+1 ii=0 contour=[] for xval in x: contour.append([xval,y[ii]]) ii=ii+1 coeffs = pyefd.elliptic_fourier_descriptors(contour, order=15,normalize=True) pyefd.plot_efd(coeffs) coeffs=coeffs.flatten()[3:] save = open("input.dat", "a") np.savetxt(save, coeffs.reshape(1, coeffs.shape[0])) np.save # save card diagnosis into output file save2 = open("output.dat", "a") output = np.zeros([1, 13], dtype=np.float32) if Diagnosis ==1: np.savetxt(save2, output.reshape(1, output.shape[1]), newline = "\r") elif Diagnosis ==2: output[0,0]=1 np.savetxt(save2, output.reshape(1, output.shape[1]), newline = "\r") elif Diagnosis ==3: output[0,1]=1