def ps3_1_b(printing=True): # a) estimate camera projection matrix pts_2d = load_file('input/pts2d-pic_a.txt') pts_3d = load_file('input/pts3d.txt') # test results using a least squares solver for dif. number of calibration # points for 10 iterations M_8, res_8 = best_M(pts_2d, pts_3d, num_calibration_pts=8, num_test_pts=4, iterations=10) M_12, res_12 = best_M(pts_2d, pts_3d, num_calibration_pts=12, num_test_pts=4, iterations=10) M_16, res_16 = best_M(pts_2d, pts_3d, num_calibration_pts=16, num_test_pts=4, iterations=10) results_dict = OrderedDict([('res_8', res_8), ('M_8', M_8.flatten()), ('res_12', res_12), ('M_12', M_12.flatten()), ('res_16', res_16), ('M_16', M_16.flatten())]) residuals = (res_8, res_12, res_16) Ms = (M_8, M_12, M_16) res, M = min((res, M) for (res, M) in zip(residuals, Ms)) if printing: print( 'Residuals:\nfor 8 pts: %.5f\nfor 12 pts: %.5f\nfor 16 pts: %.5f\n' % (res_8, res_12, res_16)) print('Best Projection Matrix\nM =\n%s\n' % M) return M, res
def ps3_2_d(): # load points pts_a = np.array(load_file('input/pts2d-pic_a.txt')) pts_b = np.array(load_file('input/pts2d-pic_b.txt')) # Calculate normalization matrices m_a = np.mean(pts_a, axis=0) m_b = np.mean(pts_b, axis=0) pts_a_temp = np.subtract(pts_a, m_a[None, :]) pts_b_temp = np.subtract(pts_b, m_b[None, :]) s_a = 1 / np.abs(np.std(pts_a_temp, axis=0)).max() s_b = 1 / np.abs(np.std(pts_b_temp, axis=0)).max() S_a = np.diag([s_a, s_a, 1]) S_b = np.diag([s_b, s_b, 1]) C_a = np.array([[1, 0, -m_a[0]], [0, 1, -m_a[1]], [0, 0, 1]]) C_b = np.array([[1, 0, -m_b[0]], [0, 1, -m_b[1]], [0, 0, 1]]) T_a = np.dot(S_a, C_a) T_b = np.dot(S_b, C_b) # convert points to homogenious coordinates pts_a = np.column_stack((pts_a_temp, np.ones(pts_a.shape[0]))) pts_b = np.column_stack((pts_b_temp, np.ones(pts_b.shape[0]))) # Normalize the points (20x3)*(3x3) pts_a_norm = np.dot(pts_a, T_a) pts_b_norm = np.dot(pts_b, T_b) # Estimate fundamental matrix F = least_squares_F_solver(pts_a_norm, pts_b_norm) # Convert the fundamental matrix to Rank=2 U, S, V = np.linalg.svd(F) S[-1] = 0 S = np.diag(S) F = np.dot(np.dot(U, S), V) if printing: print('Ta=\n%s\n' % T_a) print('Tb=\n%s\n' % T_b) print('F=\n%s\n' % F) return T_a, T_b, F
def ps3_2_a(printing=True): # estimate the Fundamental Matrix between pic_a and pic_b pts_a = load_file('input/pts2d-pic_a.txt') pts_b = load_file('input/pts2d-pic_b.txt') F = least_squares_F_solver(pts_a, pts_b) if printing: print('Fundametal Matrix with Rank=3: \n%s\n' % F) return F
def main(): points_2d = load_file('input/pts2d-norm-pic_a.txt') points_3d = load_file('input/pts3d-norm.txt') M, c = least_squares_proj_matrix(points_3d, points_2d) f = open('output/ps3-1-a-1.txt', 'w+') residual = check_point(points_3d[-1], points_2d[-1], M) f.write('Projection Matrix:\n' + str(M) + '\nresidual:\n' + str(residual)) f.close()
def main(): points_2d = load_file('input/pts2d-norm-pic_a.txt') points_3d = load_file('input/pts3d-norm.txt') repeats = 10 k_amounts = [8, 12, 16] num_residuals = 4 results = np.zeros((repeats, len(k_amounts))) best_M = [] lowest_residual = np.inf for i in range(repeats): for k in range(len(k_amounts)): #for each of k amounts we choose points and train on them ls choosen_numbers = random.sample(range(points_2d.shape[0]), k_amounts[k]) not_choosen_numbers = [ x for x in range(points_2d.shape[0]) if x not in choosen_numbers ] choosen_points_2d = points_2d[choosen_numbers] choosen_points_3d = points_3d[choosen_numbers] not_choosen_points_2d = points_2d[not_choosen_numbers] not_choosen_points_3d = points_3d[not_choosen_numbers] #M, c = least_squares_proj_matrix(choosen_points_3d, choosen_points_2d) M = svd_proj_matrix(choosen_points_3d, choosen_points_2d) residuals = [] #then test given projection matrix on test points test_points = random.sample(range(len(not_choosen_numbers)), num_residuals) for j in range(num_residuals): test_point = test_points[j] residuals.append( check_point(not_choosen_points_3d[test_point], not_choosen_points_2d[test_point], M)) average_residual = np.average(residuals) if average_residual < lowest_residual: lowest_residual = average_residual best_M = M results[i][k] = average_residual Q = best_M[:3, :3] m = best_M[:, 3] camera_center = -np.dot(np.linalg.inv(Q), m) print(camera_center) f = open('output/ps3-1-b-1.txt', 'w+') f.write('Best Projection Matrix:\n' + str(best_M) + '\nResult table:\n' + str(results)) f.close() f = open('output/ps3-1-best_m.txt', 'w+') f.write(str(best_M).replace('[', '').replace(']', '')) f.close()
def remove_redirections(data): redirections = [] redirections0 = [] original_redirections = load_file(global_file_with_redirection) for r in original_redirections: red_array = r.split("\t") redirection_names = red_array[1].split("|") for rn in redirection_names: redirections.append("%s\t%s" % (rn.strip(), red_array[0])) redirections.append("%s\t%s" % (rn.strip().lower(), red_array[0])) redirections0.append(red_array[0]) redirections0.sort() redirections.sort() original_redirections[:] = [] for d in data: if d.wikipedia_url.strip() == "": continue not_redirection = binary_search(redirections0, d.wikipedia_url) if not_redirection is -1: wiki_key = d.wikipedia_url.replace("http://en.wikipedia.org/wiki/", "").replace("_", "") final_url = binary_search(redirections, wiki_key, cross_columns=True, col_sep="\t", finding_column=0, return_column=1) if final_url is not -1: d.wikipedia_url = final_url return wiki_key = d.wikipedia_url.replace("http://en.wikipedia.org/wiki/", "").replace("_", "").lower() final_url = binary_search(redirections, wiki_key, cross_columns=True, col_sep="\t", finding_column=0, return_column=1) if final_url is not -1: d.wikipedia_url = final_url return
def ps3_2_e(): # load images img_a = cv2.imread('input/pic_a.jpg', cv2.IMREAD_COLOR) img_b = cv2.imread('input/pic_b.jpg', cv2.IMREAD_COLOR) # load points pts_a = np.array(load_file('input/pts2d-pic_a.txt')) pts_b = np.array(load_file('input/pts2d-pic_b.txt')) # convert pts to homogenious coordinates pts_a = np.column_stack((pts_a, np.ones(pts_a.shape[0]))) pts_b = np.column_stack((pts_b, np.ones(pts_b.shape[0]))) # Estimate fundamental matrix T_a, T_b, F = ps3_2_d() # create better fundamental matrix F = np.dot(T_b.T, np.dot(F, T_a)) # find the epipolar lines for each point in both images eplines_a = np.dot(F.T, pts_b.T).T eplines_b = np.dot(F, pts_a.T).T n, m, _ = img_a.shape line_L = np.cross([0, 0, 1], [n, 0, 1]) line_R = np.cross([0, m, 1], [n, m, 1]) # draw the epipolar lines on the images for line_a, line_b in zip(eplines_a, eplines_b): P_a_L = np.cross(line_a, line_L) P_a_R = np.cross(line_a, line_R) P_a_L = (P_a_L[:2] / P_a_R[2]).astype(int) P_a_R = (P_a_R[:2] / P_a_R[2]).astype(int) cv2.line(img_a, tuple(P_a_L[:2]), tuple(P_a_R[:2]), (0, 255, 0), thickness=2) P_b_L = np.cross(line_b, line_L) P_b_R = np.cross(line_b, line_R) P_b_L = (P_b_L[:2] / P_b_R[2]).astype(int) P_b_R = (P_b_R[:2] / P_b_R[2]).astype(int) cv2.line(img_b, tuple(P_b_L[:2]), tuple(P_b_R[:2]), (0, 255, 0), thickness=2) # save the images with the highlighted epipolar lines cv2.imwrite('output/ps3-2-e-1.png', img_a) cv2.imwrite('output/ps3-2-e-2.png', img_b) print('Fundametal Matrix F=\n%s\n' % F) cv2.imshow('', np.hstack((img_a, img_b))) cv2.waitKey(0) cv2.destroyAllWindows() print('Images with highlighted epipolar lines saved successfully!')
def ps3_1_a(): # a) estimate camera projection matrix pts_2d = load_file('input/pts2d-norm-pic_a.txt') pts_3d = load_file('input/pts3d-norm.txt') # test results using a least squares solver M, res = least_squares_M_solver(pts_2d, pts_3d) pt_2d_proj = np.dot(M, np.append(pts_3d[-1], 1)) pt_2d_proj = pt_2d_proj[:2] / pt_2d_proj[2] res = np.linalg.norm(pts_2d[-1] - pt_2d_proj) print('Results with least squares:') print('M=\n%s' % M) print('Point %s projected to point %s' % (pts_2d[-1], pt_2d_proj)) print('Residual: %.4f\n' % res) # test results using a least squares solver M = svd_M_solver(pts_2d, pts_3d) pt_2d_proj = np.dot(M, np.append(pts_3d[-1], 1)) pt_2d_proj = pt_2d_proj[:2] / pt_2d_proj[2] res = np.linalg.norm(pts_2d[-1] - pt_2d_proj) print('Results with SVD:') print('M=\n%s' % M) print('Point %s projected to point %s' % (pts_2d[-1], pt_2d_proj)) print('Residual: %.4f\n' % res)
def prepare_help_files(): original_redirections = load_file(global_file_with_redirection) for r in original_redirections: red_array = r.split("\t") redirection_names = red_array[1].split("|") for rn in redirection_names: redirections.append("%s\t%s" % (rn.strip(), red_array[0])) redirections.append("%s\t%s" % (rn.strip().lower(), red_array[0])) redirections0.append(red_array[0]) redirections0.sort() redirections.sort() original_redirections[:] = []
from math import sin import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from load_file import * #my liblary n_train = 100000 n_test = 10000 n_state = 0 DATA = 1 if DATA == 1: log_file = '../../log/state_action_1dof.log' n_state = 1 X_train, y_train, X_test, y_test = load_file(log_file, n_state=n_state, n_train=n_train, n_test=n_test, sampling="curiosity") elif DATA == 2: log_file = '../../log/state_action_2dof.log' n_state = 2 X_train, y_train, X_test, y_test = load_file(log_file, n_state=n_state, n_train=n_train, n_test=n_test, sampling="curiosity") elif DATA == 0: X_train, X_test = 10 * (np.random.random(n_train).reshape( (-1, 1)) - 0.5), 10 * (np.random.random(n_test).reshape((-1, 1)) - 0.5)
exit() monotonicSortMap = {'rate': 'p', 'deadline': 'd'} monotonicType = 'rate' if len(argv) < 3: print('NOTICE: third parameter "rate" or "deadline" monotonic type ' + 'was not given, using rate monotonic by default') else: monotonicType = argv[2] ## # Load tasks and sort so we can determine priorities. ## tasks = load_file(argv[1]) tasks = sorted(tasks, key=lambda x: x[monotonicSortMap[monotonicType]]) ## # Calculate WCRT. ## unfeasibleCount = 0 for i in range(0, len(tasks)): print('\nTask ' + str(i + 1)) n = 0 wP = tasks[i]['e'] + tasks[i]['B'] while True:
def build_model_from_file(self, fname, random_weights): self.pos_dict, self.id_node_dict, self.node_layers, self.leaf_id_order, self.input_layers, self.input_order = load_file( fname, random_weights)