# -*- coding: utf-8 -*- """ Created on Sat Apr 20 14:16:19 2019 @author: qinzhen """ import helper as hlp #Step1 产生数据 #参数 rad = 10 thk = 5 sep = 5 #产生数据 X, y = hlp.generatedata(rad, thk, sep, 100) knn = hlp.KNeighborsClassifier_(1) knn.fit(X, y) hlp.draw(X, y, knn) knn = hlp.KNeighborsClassifier_(3) knn.fit(X, y) hlp.draw(X, y, knn)
#!/usr/bin/env python # -*- coding=utf-8 -*- from config import VIDEO_ID, NUM_WINNERS from helper import get_commenters, draw, get_beijing_time if __name__ == '__main__': print("北京时间: {}".format(get_beijing_time())) with open("cookies.txt", "r") as f: raw = f.read().strip() cookies = dict(cookies_are=raw) followed, not_followed = get_commenters(VIDEO_ID, cookies) pool = set(followed.keys()) winners = draw(pool, NUM_WINNERS) print("*************************************") print("抽奖结果: ") for i in range(len(winners)): print("第{}位获奖观众: {} - https://space.bilibili.com/{}".format( i + 1, followed[winners[i]], winners[i]))
# -*- coding: utf-8 -*- """ Created on Thu May 2 09:25:37 2019 @author: qinzhen """ import numpy as np import helper as hlp X = np.array([[0, 0], [0, 1], [5, 5]]).astype("float") y = np.array([1, 1, -1]) #(a) knn = hlp.KNeighborsClassifier_(1) knn.fit(X, y) hlp.draw(X, y, knn) #(b) scaler = hlp.StandardScaler_() X1 = scaler.fit_transform(X) knn = hlp.KNeighborsClassifier_(1) knn.fit(X1, y) hlp.draw(X, y, knn, flag=2, preprocess=scaler) #(c) pca = hlp.PCA_(1) pca.fit(X) X2 = pca.transform(X) knn = hlp.KNeighborsClassifier_(1) knn.fit(X2, y)
pool = set([i for i in range(TEST_POOL_SIZE)]) def test_config_params(): if TEST_POOL_SIZE <= 0 or TEST_WINNERS <= 0 or TEST_EXPERIMENTS <= 0: print("测试参数设定错误,各项测试参数均应大于零") raise ValueError if TEST_POOL_SIZE < TEST_WINNERS: print("测试参数设定错误,抽奖人数应小于等于奖池人数") raise ValueError if __name__ == '__main__': try: test_config_params() except ValueError: sys.exit(1) print("测试开始...") print("将进行{}次实验,每次抽取{}名获奖观众".format(TEST_EXPERIMENTS, TEST_WINNERS)) mean = TEST_EXPERIMENTS * TEST_WINNERS // TEST_POOL_SIZE print("理想状况下,每位观众被抽中次数应接近{}".format(mean)) results = {} for i in range(TEST_EXPERIMENTS): result = draw(pool, TEST_WINNERS) for key in result: results[key] = results.get(key, 0) + 1 print("实验结束,结果如下:") print("观众最少被抽中{}次,最多被抽中{}次".format(min(results.values()), max(results.values())))
""" Created on Sat Apr 20 12:48:23 2019 @author: qinzhen """ #(a) import numpy as np import helper as hlp X = np.array([[1, 0], [0, 1], [0, -1], [-1, 0], [0, 2], [0, -2], [-2, 0]]) y = np.array([-1, -1, -1, -1, 1, 1, 1]) knn = hlp.KNeighborsClassifier_(1) knn.fit(X, y) hlp.draw(X, y, knn) knn = hlp.KNeighborsClassifier_(3) knn.fit(X, y) hlp.draw(X, y, knn) #(b) #特征转换 Z = np.c_[np.sqrt(X[:, 0]**2 + X[:, 1]**2), np.arctan(X[:, 1] / (X[:, 0] + 10**(-8)))] knn = hlp.KNeighborsClassifier_(1) knn.fit(Z, y) hlp.draw(X, y, knn, flag=0) knn = hlp.KNeighborsClassifier_(3) knn.fit(Z, y)
print("You had this char before") for item in hangedPortion: if (len(item) > 0): print(item) else: choosed.append(char) if (char in word): indexList = helper.find(word, char) for i in indexList: tempGuess[i] = char helper.newLine() if ('_' not in tempGuess): helper.clear('You won!!!') print('The word was ' + word) helper.newLine() helper.draw(notHanged) helper.newLine() break else: helper.clear() status(2) for item in hangedPortion: if (len(item) > 0): print(item) else: wrongs -= 1 helper.clear() status(1) print('Wrong. You are left {} shots.'.format(wrongs)) if (len(hangedgrad) > 1): hangedPortion.append(hangedgrad.pop())
def main(): # cap_img = cv2.imread('Images/Test_Markers/7.jpeg') camera_parameters, dist = he.camera_calibration('Images/Calibration') dir_name = os.getcwd() obj = OBJ(os.path.join(dir_name, 'Models/fox/fox.obj'), swapyz=True) model_list = he.create_list('Images') model_keypoints = he.find_model_keypoints(model_list) # print('b') if not args.problem: cap = cv2.VideoCapture(0) while True: # read the current frame ret, frame = cap.read() if not ret: print("Unable to capture video") return cnt = None temp = he.find_marker(he.convert2grayscale(frame), model_list, model_keypoints, camera_parameters, dist) if temp is not None: cnt, homographies, models = temp # compute Homography if enough matches are found if cnt is not None: # if a valid homography matrix was found render cube on model plane for x, h, m in zip(cnt, homographies, models): try: projection = he.projection_matrix(camera_parameters, h) frame = he.render(frame, obj, projection, m, False) # rect = cnt[0] # pseudo_model = h.crop_img(frame.copy(), rect) # r_p, c_p = pseudo_model.shape[0], pseudo_model.shape[1] # pts = [x[0] for x in rect] # pts2 = [[0, 0], [0, r_p], [c_p, r_p], [c_p, 0]] # projection = cv2.getPerspectiveTransform(pts, pts2) break except: pass # draw first 10 matches. if args.rectangle: if cnt is not None: for x in cnt: x = he.convert_to_ndarray(x) cv2.drawContours(frame, [x], -1, (0, 255, 0), 3) points_dum = np.array([[[0, 0, 0]], [[100, 0, 0]], [[0, 100, 0]], [[0, 0, 100]]]) points_dum = np.float32( [np.float32(p) for p in points_dum]) # print(axis) newpts = cv2.perspectiveTransform( points_dum, projection) cap_img = he.draw( frame, newpts[0][0], [newpts[1][0], newpts[2][0], newpts[3][0]]) break # show result else: print('No marker found') cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() elif args.problem: # print('c') no = input('Enter image no. to process: ') # img nos - cap_img = cv2.imread('Images/Test_Markers/Prob2/' + str(no) + '.jpeg') camera_parameters, dist = he.camera_calibration('Images/Calibration') model_list = he.create_list('Images') model_keypoints = he.find_model_keypoints(model_list) cnt = None temp = he.find_marker(he.convert2grayscale(cap_img), model_list, model_keypoints, camera_parameters, dist) if temp is not None: cnt, homographies, models = temp cnt = [cnt[1], cnt[0]] homographies = [homographies[1], homographies[0]] models = [models[1], models[0]] if cnt is not None: if (len(cnt) == 2): ro1, co1 = models[0].shape ro2, co2 = models[1].shape proj1 = he.projection_matrix(camera_parameters, homographies[0]) proj2 = he.projection_matrix(camera_parameters, homographies[1]) points1 = np.array([[[co1 / 2, ro1 / 2, 0]]]) points1 = np.float32([np.float32(p) for p in points1]) origin1 = np.array( cv2.perspectiveTransform(points1, proj1)[0][0]) points2 = np.array([[[0, 0, 0]], [[100, 0, 0]], [[0, 100, 0]], [[0, 0, 100]]]) points2 = np.float32([np.float32(p) for p in points2]) axes2 = cv2.perspectiveTransform(points2, proj2) origin2 = axes2[0][0] ptz = axes2[3][0] ###### if args.rectangle: projection = proj1 points_dum = np.array([[[0, 0, 0]], [[100, 0, 0]], [[0, 100, 0]], [[0, 0, 100]]]) points_dum = np.float32( [np.float32(p) for p in points_dum]) newpts = cv2.perspectiveTransform(points_dum, projection) cap_img = he.draw( cap_img, newpts[0][0], [newpts[1][0], newpts[2][0], newpts[3][0]]) projection = proj2 points_dum = np.array([[[0, 0, 0]], [[100, 0, 0]], [[0, 100, 0]], [[0, 0, 100]]]) points_dum = np.float32( [np.float32(p) for p in points_dum]) newpts = cv2.perspectiveTransform(points_dum, projection) cap_img = he.draw( cap_img, newpts[0][0], [newpts[1][0], newpts[2][0], newpts[3][0]]) ###### origin2 = np.array(origin2) origin1_x = origin1[0] origin1_y = origin1[1] origin2_x = origin2[0] ptz_x = ptz[0] origin2_y = origin2[1] ptz_y = ptz[1] moving_slope = (ptz_y - origin2_y) / (ptz_x - origin2_x) # moving_slope = (origin2_y-origin1_y)/(origin2_x-origin1_x) moving_positive = origin1 + STEP_SIZE * \ np.array([1, moving_slope]) moving_negative = origin1 - STEP_SIZE * \ np.array([1, moving_slope]) distance_pos = np.linalg.norm(origin2 - moving_positive) distance_neg = np.linalg.norm(origin2 - moving_negative) if (distance_pos < distance_neg): counter = 0 old_distance = math.inf while True: print('Slope:' + str(moving_slope)) frame = cap_img.copy() moving_positive = origin1 + counter * STEP_SIZE * \ np.array([1, moving_slope]) new_distance = np.linalg.norm(origin2 - moving_positive) print('new:' + str(new_distance)) print('old:' + str(old_distance)) if (new_distance > old_distance): print('break') break old_distance = new_distance counter += 1 shift = moving_positive - origin1 frame = he.render(frame, obj, proj1, models[0], False, shift[0], shift[1]) print(shift) cv2.imshow('Moving_obj', frame) cv2.waitKey(1) else: counter = 0 old_distance = math.inf while True: print('Slope:' + str(moving_slope)) frame = cap_img.copy() moving_negative = origin1 - counter * STEP_SIZE * \ np.array([1, moving_slope]) new_distance = np.linalg.norm(origin2 - moving_negative) print('new:' + str(new_distance)) print('old:' + str(old_distance)) if (new_distance > old_distance): print('break') break old_distance = new_distance counter += 1 shift = moving_negative - origin1 frame = he.render(frame, obj, proj1, models[0], False, shift[0], shift[1]) print(shift) cv2.imshow('Moving_obj', frame) cv2.waitKey(1) else: print('Less than 2 Markers Found') cv2.destroyAllWindows() return 0
y_cd.append(-1) else: break return np.array(X_cd), np.array(y_cd) #### (b) n = 1000 X, y = hlp.Data(n, 1, scale=0.5) plt.scatter(X[:, 0], X[:, 1], edgecolor='k', c=y) plt.show() #原始数据的分类结果 nn = hlp.KNeighborsClassifier_(1) nn.fit(X, y) hlp.draw(X, y, nn, n=500, flag=1) #### CNN1 #condense data的分类结果 X_cd, y_cd = CNN1(X, y) nn = hlp.KNeighborsClassifier_(1) nn.fit(X_cd, y_cd) hlp.draw(X_cd, y_cd, nn, n=500, flag=1) #### CNN2 #condense data的分类结果 X_cd, y_cd = CNN2(X, y) nn = hlp.KNeighborsClassifier_(1) nn.fit(X_cd, y_cd) hlp.draw(X_cd, y_cd, nn, n=500, flag=1) '''
y_test[y_test != 1] = -1 #### (b) #训练模型 nn = hlp.KNeighborsClassifier_(3) nn.fit(X_train, y_train) y_test_pred = nn.predict(X_test) y_train_pred = nn.predict(X_train) #计算错误率 ein = np.mean(y_train != y_train_pred) etest = np.mean(y_test != y_test_pred) print("Ein of 3-NN is {}".format(ein)) print("Etest of 3-NN is {}".format(etest)) #作图 hlp.draw(X_train, y_train, nn, n=500, flag=1) #### (c) X_cd, y_cd = hlp.CNN(X_train, y_train, k=3) #训练模型 nn = hlp.KNeighborsClassifier_(3) nn.fit(X_cd, y_cd) y_test_pred = nn.predict(X_test) y_train_pred = nn.predict(X_train) #计算错误率 ein = np.mean(y_train != y_train_pred) etest = np.mean(y_test != y_test_pred) print("Ein of C-NN is {}".format(ein)) print("Etest of C-NN is {}".format(etest)) #作图