From 313060fbbb0188212b2c4820baaaa7352fa9d51a Mon Sep 17 00:00:00 2001 From: Kei Okada Date: Sat, 11 Jul 2020 14:41:48 +0900 Subject: [PATCH] fix for python3, use 2to3 -f print, 2to3 -f except --- .../src/objectdetection_tf_publisher.py | 2 +- cr_calibration/cr_calibration.py | 8 +-- doc/conf.py | 2 +- .../depth_error_calibration.py | 24 ++++---- jsk_pcl_ros/scripts/draw_3d_circle.py | 2 +- jsk_pcl_ros/scripts/dump_depth_error.py | 8 +-- .../scripts/in_hand_recognition_manager.py | 8 +-- jsk_pcl_ros/scripts/plot_depth_error.py | 4 +- jsk_pcl_ros/scripts/plot_gaussian.py | 2 +- jsk_pcl_ros/scripts/renew_tracking.py | 2 +- .../scripts/tower_detect_viewer_server.py | 4 +- .../node_scripts/binpack_rect_array.py | 2 +- jsk_perception/node_scripts/matchtemplate.py | 10 ++-- .../node_scripts/random_forest_server.py | 2 +- .../node_scripts/solidity_rag_merge.py | 2 +- .../sample/random_forest_client_sample.py | 14 ++--- .../scripts/check_cascadeclassifier.py | 6 +- jsk_perception/scripts/create_bof_dataset.py | 4 +- jsk_perception/scripts/create_sift_dataset.py | 2 +- .../scripts/opencv_traindata_rejector.py | 2 +- .../scripts/sklearn_classifier_trainer.py | 6 +- jsk_perception/test/test_sparse_image.py | 4 +- posedetectiondb/src/GatherDetectionResults.py | 10 ++-- posedetectiondb/src/PointPoseExtraction.py | 56 +++++++++---------- .../src/PoseFromCorrespondences.py | 32 +++++------ 25 files changed, 109 insertions(+), 109 deletions(-) diff --git a/checkerboard_detector/src/objectdetection_tf_publisher.py b/checkerboard_detector/src/objectdetection_tf_publisher.py index d180a712b6..f38782074f 100755 --- a/checkerboard_detector/src/objectdetection_tf_publisher.py +++ b/checkerboard_detector/src/objectdetection_tf_publisher.py @@ -86,7 +86,7 @@ def send_dynamic_tf_request(self, pos_x, pos_y, pos_z, ori_x, ori_y, ori_z, ori_ try: res = set_dynamic_tf(set_tf_request) except rospy.ServiceException as exc: - print("Service did not process request: " + str(exc)) + print(("Service did not process request: " + str(exc))) if __name__== '__main__': rospy.init_node('objectdetection_tf_publisher', anonymous=True) diff --git a/cr_calibration/cr_calibration.py b/cr_calibration/cr_calibration.py index 9f154f419d..1de92318cc 100755 --- a/cr_calibration/cr_calibration.py +++ b/cr_calibration/cr_calibration.py @@ -91,7 +91,7 @@ def queue_cr(self, limg, linfo, rimg, rinfo): return False dist = self.calc_distance(self.static_pose, lframe) - print dist + print(dist) if dist > 0.012: self.frame_list = [] self.static_pose = None @@ -116,8 +116,8 @@ def queue_cr(self, limg, linfo, rimg, rinfo): # finish check if len(self.result_list) > 7 and self.last_err < 0.1: rospy.loginfo("Finished size = %d, err = %f" % (len(self.result_list), self.last_err)) - print "translation: [%f, %f, %f]\nrotation: [%f, %f, %f, %f]" % (ret.p.x(), ret.p.y(), ret.p.z(), qx, qy, qz, qw) - print "(make-coords :pos #f(%f %f %f) :rot (quaternion2matrix #f(%f %f %f %f)))" % (1000*ret.p.x(), 1000*ret.p.y(), 1000*ret.p.z(), qw, qx, qy, qz) + print("translation: [%f, %f, %f]\nrotation: [%f, %f, %f, %f]" % (ret.p.x(), ret.p.y(), ret.p.z(), qx, qy, qz, qw)) + print("(make-coords :pos #f(%f %f %f) :rot (quaternion2matrix #f(%f %f %f %f)))" % (1000*ret.p.x(), 1000*ret.p.y(), 1000*ret.p.z(), qw, qx, qy, qz)) #print "" % (ret.p.x(), ret.p.y(), ret.p.z(), qw, qx, qy, qz) exit(-1) @@ -195,7 +195,7 @@ def find_checkerboard_pose(self, ros_image, cam_info): #we need to convert the ros image to an opencv image try: image = self.bridge.imgmsg_to_cv(ros_image, "mono8") - except CvBridgeError, e: + except CvBridgeError as e: rospy.logerror("Error importing image %s" % e) return diff --git a/doc/conf.py b/doc/conf.py index dc048b4781..d396d08a8b 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -179,7 +179,7 @@ # Additional stuff for the LaTeX preamble. 'preamble': "".join(( - '\usepackage[utf8]{inputenc}', + "\\usepackage[utf8]{inputenc}", # NO-BREAK SPACE '\DeclareUnicodeCharacter{00A0}{ }', # BOX DRAWINGS LIGHT VERTICAL AND RIGHT diff --git a/jsk_pcl_ros/scripts/check_depth_error/depth_error_calibration.py b/jsk_pcl_ros/scripts/check_depth_error/depth_error_calibration.py index cf98d57e9d..86d4800cfb 100755 --- a/jsk_pcl_ros/scripts/check_depth_error/depth_error_calibration.py +++ b/jsk_pcl_ros/scripts/check_depth_error/depth_error_calibration.py @@ -125,7 +125,7 @@ def setParameter(classifier): c0 = classifier.intercept_ param = DepthCalibrationParameter() if not isValidClassifier(classifier): - print "parameters are list" + print("parameters are list") return if model == "linear": param.coefficients2 = [0, 0, 0, 0, 0] @@ -168,7 +168,7 @@ def processData(x, y, u, v, cu, cv, fit = True): zs = value_cache[(uu, vv)] for z in zs: if abs(z - y) < eps_z: - print "duplicated value" + print("duplicated value") return else: value_cache[(uu, vv)].append(y) @@ -180,22 +180,22 @@ def processData(x, y, u, v, cu, cv, fit = True): c_us.append(cu) c_vs.append(cv) if u > u_min and u < u_max and v < v_max and v > v_min: - print (x, y) + print((x, y)) xs.append(genFeatureVector(x, u, v, cu, cv)) ys.append(y) if fit: classifier.fit(xs, ys) try: setParameter(classifier) - except rospy.service.ServiceException, e: + except rospy.service.ServiceException as e: rospy.logfatal("failed to call service: %s" % (e.message)) try: - print modelEquationString(classifier) - except Exception, e: + print(modelEquationString(classifier)) + except Exception as e: rospy.logwarn("failed to print model: %s" % e.message) else: - print "(%d, %d) is out of range" % (u, v) + print("(%d, %d) is out of range" % (u, v)) def callback(msg): global xs, ys, classifier, u_min, u_max, v_min, v_max, raw_xs @@ -338,7 +338,7 @@ def updatePlot(): plot_img.shape = (h, w, 3) plt.close() pub_error_plot.publish(bridge.cv2_to_imgmsg(plot_img, "bgr8")) - except Exception, e: + except Exception as e: rospy.logerr(e.message) def generateFrequencyMap(): @@ -379,7 +379,7 @@ def main(): height = args.height if args.models: for m in MODELS: - print m + print(m) return model = args.model if model not in MODELS: @@ -409,14 +409,14 @@ def main(): classifier.fit(xs, ys) try: setParameter(classifier) - except rospy.service.ServiceException, e: + except rospy.service.ServiceException as e: rospy.logfatal("failed to call service: %s" % (e.message)) try: plt.show() finally: if not args.csv: csv_filename = "calibration-%s.csv" % datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') - print "Save calibration parameters to %s" % (csv_filename) + print("Save calibration parameters to %s" % (csv_filename)) with open(csv_filename, "w") as f: for x, y, u, v, cu, cv in zip(raw_xs, ys, us, vs, c_us, c_vs): f.write("%f,%f,%d,%d,%f,%f\n" % (x, y, u, v, cu, cv)) @@ -424,7 +424,7 @@ def main(): if dump is True or \ (dump == "query" and query_yes_no("Dump result into yaml file?")): yaml_filename = "calibration_parameter_%s.yaml" % datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S') - print "writing to %s" % yaml_filename + print("writing to %s" % yaml_filename) c = classifier.coef_ if model == "quadratic-uv-abs" or model == "quadratic-uv-quadratic-abs": use_abs = "True" diff --git a/jsk_pcl_ros/scripts/draw_3d_circle.py b/jsk_pcl_ros/scripts/draw_3d_circle.py index 4301faebd4..f86559892f 100755 --- a/jsk_pcl_ros/scripts/draw_3d_circle.py +++ b/jsk_pcl_ros/scripts/draw_3d_circle.py @@ -16,7 +16,7 @@ import math def usage(): - print "Usage: ", sys.argv[0], "id frame_id radius [r, g, b]" + print("Usage: ", sys.argv[0], "id frame_id radius [r, g, b]") class Drawer3DCircle: RESOLUTION = 20 diff --git a/jsk_pcl_ros/scripts/dump_depth_error.py b/jsk_pcl_ros/scripts/dump_depth_error.py index badf73cf30..02c2c3cade 100755 --- a/jsk_pcl_ros/scripts/dump_depth_error.py +++ b/jsk_pcl_ros/scripts/dump_depth_error.py @@ -19,13 +19,13 @@ def callback(msg): for bin_index, msg_and_errs in bins.items(): if len(msg_and_errs) < 5: continue - print "Bin: {0}m ~ {1}m".format(grid * bin_index, grid * (bin_index + 1)) - print " Sample:", len(msg_and_errs) + print("Bin: {0}m ~ {1}m".format(grid * bin_index, grid * (bin_index + 1))) + print(" Sample:", len(msg_and_errs)) errs = [err for (msg, err) in msg_and_errs] mean = np.mean(errs, axis=0) stddev = np.std(errs, axis=0) - print " Mean:", mean - print " Stddev:", stddev + print(" Mean:", mean) + print(" Stddev:", stddev) data.xs.append(msg.true_depth) data.ys.append(msg.observed_depth) pub.publish(data) diff --git a/jsk_pcl_ros/scripts/in_hand_recognition_manager.py b/jsk_pcl_ros/scripts/in_hand_recognition_manager.py index 225734625d..4b63d97684 100755 --- a/jsk_pcl_ros/scripts/in_hand_recognition_manager.py +++ b/jsk_pcl_ros/scripts/in_hand_recognition_manager.py @@ -55,8 +55,8 @@ def pose_diff_cb(pose_stamped): try: teacher_pose_stamped.header.stamp = rospy.Time(0) teacher_pose_stamped_recog_frame = listener.transformPose(pose_stamped.header.frame_id, teacher_pose_stamped) - except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException, tf.Exception), e: - print "tf error: %s" % e + except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException, tf.Exception) as e: + print("tf error: %s" % e) return teacher_pose_mat = (get_mat_from_pose(teacher_pose_stamped_recog_frame.pose)) diff_pose_mat = (get_mat_from_pose(pose_stamped.pose)) @@ -70,8 +70,8 @@ def pose_diff_cb(pose_stamped): try: new_pose_stamped.header.stamp = rospy.Time(0) new_pose_stamped_for_renew = listener.transformPose(teacher_pose_stamped.header.frame_id, new_pose_stamped) - except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException, tf.Exception), e: - print "tf error: %s" % e + except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException, tf.Exception) as e: + print("tf error: %s" % e) return pose_teacher_cb(new_pose_stamped_for_renew) renew_flag = False diff --git a/jsk_pcl_ros/scripts/plot_depth_error.py b/jsk_pcl_ros/scripts/plot_depth_error.py index 2b3fdc883a..bf7d3e9897 100755 --- a/jsk_pcl_ros/scripts/plot_depth_error.py +++ b/jsk_pcl_ros/scripts/plot_depth_error.py @@ -36,8 +36,8 @@ plt.plot(X, line_y_ransac, "r--", label="{0} x + {1}".format(model_ransac.estimator_.coef_[0][0], model_ransac.estimator_.intercept_[0])) - print "{0} x + {1}".format(model_ransac.estimator_.coef_[0][0], - model_ransac.estimator_.intercept_[0]) + print("{0} x + {1}".format(model_ransac.estimator_.coef_[0][0], + model_ransac.estimator_.intercept_[0])) plt.grid() plt.xlabel("Distance [m]") plt.ylabel("Standard Deviation [m]") diff --git a/jsk_pcl_ros/scripts/plot_gaussian.py b/jsk_pcl_ros/scripts/plot_gaussian.py index fb0d7da5b0..ccdd54320f 100755 --- a/jsk_pcl_ros/scripts/plot_gaussian.py +++ b/jsk_pcl_ros/scripts/plot_gaussian.py @@ -7,7 +7,7 @@ import sys if len(sys.argv) != 3: - print "plot_gaussian.py mean variance" + print("plot_gaussian.py mean variance") sys.exit(1) mean = float(sys.argv[1]) variance = float(sys.argv[2]) diff --git a/jsk_pcl_ros/scripts/renew_tracking.py b/jsk_pcl_ros/scripts/renew_tracking.py index b8b4ecc57c..a1fe4eea9f 100755 --- a/jsk_pcl_ros/scripts/renew_tracking.py +++ b/jsk_pcl_ros/scripts/renew_tracking.py @@ -18,7 +18,7 @@ def cloud_cb(cloud): setCloud = rospy.ServiceProxy('particle_filter_tracker/renew_model', SetPointCloud2) setCloud(cloud, track_target_name) rospy.loginfo("Success renew_tracking service"); - except rospy.ServiceException, e: + except rospy.ServiceException as e: rospy.loginfo("Failed to call renew_tracking service") if __name__ == "__main__": diff --git a/jsk_pcl_ros/scripts/tower_detect_viewer_server.py b/jsk_pcl_ros/scripts/tower_detect_viewer_server.py index dd9c07663b..7a082aae6b 100755 --- a/jsk_pcl_ros/scripts/tower_detect_viewer_server.py +++ b/jsk_pcl_ros/scripts/tower_detect_viewer_server.py @@ -301,8 +301,8 @@ def clickCB(self, msg): def imageCB(self, data): try: self.cv_image = self.bridge.imgmsg_to_cv(data, "bgr8") - except CvBridgeError, e: - print e + except CvBridgeError as e: + print(e) def publishState(self): self.state.publish() def spin(self): diff --git a/jsk_perception/node_scripts/binpack_rect_array.py b/jsk_perception/node_scripts/binpack_rect_array.py index 4116dae5ff..d7854b9efb 100755 --- a/jsk_perception/node_scripts/binpack_rect_array.py +++ b/jsk_perception/node_scripts/binpack_rect_array.py @@ -132,7 +132,7 @@ def bin_pack(self, rects): #blocks.sort(key=lambda x: x.rect.width*x.rect.height, reverse=True) blocks.sort(reverse=True) packer.fit(blocks) - print (packer.root.rect.width, packer.root.rect.height) + print((packer.root.rect.width, packer.root.rect.height)) return (packer.root.rect, blocks) # for block in blocks: # if block.fit_location: diff --git a/jsk_perception/node_scripts/matchtemplate.py b/jsk_perception/node_scripts/matchtemplate.py index c96e7f7f47..944c7b1293 100755 --- a/jsk_perception/node_scripts/matchtemplate.py +++ b/jsk_perception/node_scripts/matchtemplate.py @@ -149,8 +149,8 @@ def set_reference (self, rect): cv_image = self.bridge.imgmsg_to_cv2( self.reference_image_msg, "bgr8") self.set_template('',ref_image=cv_image, ref_rect=rect) - except CvBridgeError, e: - print e + except CvBridgeError as e: + print(e) # # Callback Functions (lock require) @@ -164,7 +164,7 @@ def set_reference_point_callback (self, msg): # PointStamped pt[1]-self.default_template_size[1]/2, self.default_template_size[0], self.default_template_size[1]) self.set_reference(rect) - print rect + print(rect) search_rect = (pt[0]-self.default_search_size[0]/2, pt[1]-self.default_search_size[1]/2, self.default_search_size[0],self.default_search_size[1]) @@ -331,8 +331,8 @@ def ser_image_callback (self, msg): :reference_size[1], :reference_size[0], :] = \ reference_image.copy() - except CvBridgeError, e: - print e + except CvBridgeError as e: + print(e) self.lockobj.release() diff --git a/jsk_perception/node_scripts/random_forest_server.py b/jsk_perception/node_scripts/random_forest_server.py index a933a8e81e..60c090f4bc 100755 --- a/jsk_perception/node_scripts/random_forest_server.py +++ b/jsk_perception/node_scripts/random_forest_server.py @@ -40,7 +40,7 @@ def initWithFileModel(cls, filename): def classifyData(self, req): ret = [] for data in req.data: - print data + print(data) ret.append(" ".join([ str(predict_data) for predict_data in self.clf.predict([data.point])])) diff --git a/jsk_perception/node_scripts/solidity_rag_merge.py b/jsk_perception/node_scripts/solidity_rag_merge.py index 06884e0e9b..7f343d51b1 100755 --- a/jsk_perception/node_scripts/solidity_rag_merge.py +++ b/jsk_perception/node_scripts/solidity_rag_merge.py @@ -129,7 +129,7 @@ def masked_slic(img, mask, n_segments, compactness): n_labels = len(np.unique(labels)) try: mask = ndi.binary_closing(mask, structure=np.ones((3, 3)), iterations=1) - except IndexError, e: + except IndexError as e: rospy.logerr(e) return labels[mask == 0] = 0 # set bg_label diff --git a/jsk_perception/sample/random_forest_client_sample.py b/jsk_perception/sample/random_forest_client_sample.py index dab555ca56..72039aba10 100755 --- a/jsk_perception/sample/random_forest_client_sample.py +++ b/jsk_perception/sample/random_forest_client_sample.py @@ -51,17 +51,17 @@ answer = 0 req_point.point = target req.data.append(req_point) - print OKGREEN,"Send Request ====================> Answer",ENDC - print OKGREEN," ",req_point.point," : ",str(answer),ENDC + print(OKGREEN,"Send Request ====================> Answer",ENDC) + print(OKGREEN," ",req_point.point," : ",str(answer),ENDC) response = predict_data(req) - print WARNING,"Get the result : ",ENDC - print WARNING,response.classifications,ENDC + print(WARNING,"Get the result : ",ENDC) + print(WARNING,response.classifications,ENDC) succeed = int(float(response.classifications[0])) == answer if succeed: - print OKBLUE,"Succeed!!!",ENDC + print(OKBLUE,"Succeed!!!",ENDC) else: - print FAIL,"FAIL...",FAIL - print "--- --- --- ---" + print(FAIL,"FAIL...",FAIL) + print("--- --- --- ---") # Config for plotting fig = plt.figure() diff --git a/jsk_perception/scripts/check_cascadeclassifier.py b/jsk_perception/scripts/check_cascadeclassifier.py index 4e1fb93c07..c75486c003 100755 --- a/jsk_perception/scripts/check_cascadeclassifier.py +++ b/jsk_perception/scripts/check_cascadeclassifier.py @@ -6,7 +6,7 @@ def main(): if len(sys.argv) < 3: - print "Usage: check_cascadeclassifier.py cascade.xml [image_files ...]" + print("Usage: check_cascadeclassifier.py cascade.xml [image_files ...]") sys.exit(1) classifier_file = sys.argv[1] files = sys.argv[2:] @@ -20,9 +20,9 @@ def main(): cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2) cv2.imshow('img', img) cv2.waitKey(100) - except KeyboardInterrupt, e: + except KeyboardInterrupt as e: raise e - except Exception, e: + except Exception as e: pass if __name__ == "__main__": diff --git a/jsk_perception/scripts/create_bof_dataset.py b/jsk_perception/scripts/create_bof_dataset.py index 11f667a2e2..9d1a42388c 100755 --- a/jsk_perception/scripts/create_bof_dataset.py +++ b/jsk_perception/scripts/create_bof_dataset.py @@ -30,8 +30,8 @@ def cmd_extract_bof(data_path, output, data_size=1): bof = BagOfFeatures() try: bof.fit(X) - except MemoryError, e: - print('data_size: {} ({} * {})'.format(n_data, data_size, n_data_all)) + except MemoryError as e: + print(('data_size: {} ({} * {})'.format(n_data, data_size, n_data_all))) print(e) # save bof extractor print('saving bof') diff --git a/jsk_perception/scripts/create_sift_dataset.py b/jsk_perception/scripts/create_sift_dataset.py index 4248645cf9..b672516a32 100755 --- a/jsk_perception/scripts/create_sift_dataset.py +++ b/jsk_perception/scripts/create_sift_dataset.py @@ -53,7 +53,7 @@ def create_sift_dataset(): targets, pos_list, scale_list, ori_list, desc_list = [], [], [], [], [] for i, (filename, target) in enumerate(zip(bunch_files.filenames, bunch_files.target)): - print('filename: {}, label: {}'.format(filename, target)) + print(('filename: {}, label: {}'.format(filename, target))) targets.append(target) # extract feature img = cv2.imread(filename, 0) diff --git a/jsk_perception/scripts/opencv_traindata_rejector.py b/jsk_perception/scripts/opencv_traindata_rejector.py index 481a7423fd..54ff10a3e8 100755 --- a/jsk_perception/scripts/opencv_traindata_rejector.py +++ b/jsk_perception/scripts/opencv_traindata_rejector.py @@ -30,7 +30,7 @@ def main(): width = int(width) height = int(height) if os.path.exists(fname): - print "Opening " + fname + print("Opening " + fname) img = cv2.imread(fname) cv2.rectangle(img, (x, y), (x + width, y + height), diff --git a/jsk_perception/scripts/sklearn_classifier_trainer.py b/jsk_perception/scripts/sklearn_classifier_trainer.py index a2272b1a83..f49dbd8925 100755 --- a/jsk_perception/scripts/sklearn_classifier_trainer.py +++ b/jsk_perception/scripts/sklearn_classifier_trainer.py @@ -41,14 +41,14 @@ def main(): clf = LogisticRegression() else: raise ValueError('unsupported classifier') - print('fitting {0}'.format(args.classifier)) + print(('fitting {0}'.format(args.classifier))) clf.fit(X_train, y_train) clf.target_names_ = target_names with gzip.open(args.output, 'wb') as f: pickle.dump(clf, f) y_pred = clf.predict(X_test) - print('score of classifier: {}'.format(accuracy_score(y_test, y_pred))) - print(classification_report(y_test, y_pred, target_names=target_names)) + print(('score of classifier: {}'.format(accuracy_score(y_test, y_pred)))) + print((classification_report(y_test, y_pred, target_names=target_names))) if __name__ == '__main__': diff --git a/jsk_perception/test/test_sparse_image.py b/jsk_perception/test/test_sparse_image.py index 75ada83251..4c479abedc 100755 --- a/jsk_perception/test/test_sparse_image.py +++ b/jsk_perception/test/test_sparse_image.py @@ -25,8 +25,8 @@ def _publish(self): try: self.edgemsg.header.stamp = rospy.Time.now() self.pub.publish(self.edgemsg) - except CvBridgeError, e: - print e + except CvBridgeError as e: + print(e) def _check_img_msg_diff(self, msg1, msg2): cnt = 0 diff --git a/posedetectiondb/src/GatherDetectionResults.py b/posedetectiondb/src/GatherDetectionResults.py index 4a1c965aaa..20b5067e73 100755 --- a/posedetectiondb/src/GatherDetectionResults.py +++ b/posedetectiondb/src/GatherDetectionResults.py @@ -58,7 +58,7 @@ def CreateReducedModel(self,bandwidth=0.04,bandthresh=0.01,neighthresh=0.01,show mlab.triangular_mesh(v[:,0],v[:,1],v[:,2],self.trimesh.indices,color=(0,0,0.5)) if savefile is None: savefile = self.getfilename() - print 'saving measurements to %s'%savefile + print('saving measurements to %s'%savefile) mkdir_recursive(os.path.split(savefile)[0]) savetxt(savefile,uniformpoints,'%f') def getfilename(self): @@ -162,7 +162,7 @@ def addmeasurement(self): m = Tcamera[0:3,2]*dist self.drawmeasurement(m) self.measurements.append(m) - print 'num measurements %d'%len(self.measurements) + print('num measurements %d'%len(self.measurements)) def drawmeasurement(self,m): dist = sqrt(sum(m**2)) @@ -172,7 +172,7 @@ def drawmeasurement(self,m): def savemeasurements(self,filename): self.lck.acquire() - print 'saving measurements to %s'%filename + print('saving measurements to %s'%filename) savetxt(filename,self.measurements,'%f') self.lck.release() @@ -201,10 +201,10 @@ def savemeasurements(self,filename): if cmd == 'q': break elif cmd == 'c' and options.single: - print 'adding measurement' + print('adding measurement') visualizer.addmeasurement() else: - print 'bad command',cmd + print('bad command',cmd) if options.filename: visualizer.savemeasurements(options.filename) diff --git a/posedetectiondb/src/PointPoseExtraction.py b/posedetectiondb/src/PointPoseExtraction.py index f29123f61a..0747777538 100755 --- a/posedetectiondb/src/PointPoseExtraction.py +++ b/posedetectiondb/src/PointPoseExtraction.py @@ -79,14 +79,14 @@ def extractpose(self,KK,positions,descriptors,conf,imagewidth,verboselevel=1,nei if ransaciters is None: ransaciters = 1000 if verboselevel > 0: - print 'thresh=%f,neighthresh=%f,dmin=%d,ransaciters=%d,goodinds=%d'%(thresh,neighthresh,dminexpected,ransaciters,len(goodinds)) + print('thresh=%f,neighthresh=%f,dmin=%d,ransaciters=%d,goodinds=%d'%(thresh,neighthresh,dminexpected,ransaciters,len(goodinds))) T,infodict = self.ransac(data=data,model=self,n=self.ninitial,k=ransaciters,t=thresh,d=dminexpected,return_all=True,besterr_thresh=self.besterr_thresh) inliers = infodict['inliers'] pts = transformPoints(T,data[inliers,2:5]) iz = 1/pts[:,2] projerror = mean(sqrt((data[inliers,0]-pts[:,0]*iz)**2 + (data[inliers,1]-pts[:,1]*iz)**2)) if verboselevel>0: - print 'extract time: %fs, err: %f, inliers: %d'%(time.time()-starttime,projerror,len(inliers)) + print('extract time: %fs, err: %f, inliers: %d'%(time.time()-starttime,projerror,len(inliers))) return T, projerror def fit(self,data): @@ -197,11 +197,11 @@ def ransac(self,data,model,n,k,t,d,debug=False,return_all=False,besterr_thresh=N test_err = model.get_error( test_points, maybemodel) also_idxs = test_idxs[test_err < t] # select indices of rows with accepted points if debug: - print 'test_err.min()',test_err.min() - print 'test_err.max()',test_err.max() - print 'numpy.mean(test_err)',numpy.mean(test_err) - print 'iteration %d:len(alsoinliers) = %d'%( - iterations,len(also_idxs)) + print('test_err.min()',test_err.min()) + print('test_err.max()',test_err.max()) + print('numpy.mean(test_err)',numpy.mean(test_err)) + print('iteration %d:len(alsoinliers) = %d'%( + iterations,len(also_idxs))) if len(also_idxs) > d: alsoinliers = data[also_idxs,:] betterdata = numpy.concatenate( (maybeinliers, alsoinliers) ) @@ -251,8 +251,8 @@ def __init__(self,type=None,templateppfilename=None,errorthresh=None,neighthresh self.Tright = template.get('Tright',eye(4)) self.featuretype = template.get('featuretype',None) self.pe = PointPoseExtractor(type=self.type,points3d=template['points3d'],descriptors=template['descriptors']) - except IOError,e: - print 'failed to create template: ',e + except IOError as e: + print('failed to create template: ',e) if self.templateppfilename is None: self.templateppfilename = 'template.pp' self.errorthresh = errorthresh @@ -280,8 +280,8 @@ def __init__(self,type=None,templateppfilename=None,errorthresh=None,neighthresh body = env.ReadKinBodyXMLFile(filename) env.AddKinBody(body) self.trimesh = env.Triangulate(body) - except openrave_exception,e: - print 'cannot create trimesh for %s: '%self.type,e + except openrave_exception as e: + print('cannot create trimesh for %s: '%self.type,e) finally: env.Destroy() self.cvwindow = 'ImageDisplay (L-add point,R-reset)' @@ -292,7 +292,7 @@ def __init__(self,type=None,templateppfilename=None,errorthresh=None,neighthresh def __del__(self): - print 'deleting gui' + print('deleting gui') try: self.sub_feature.unregister() except: @@ -305,11 +305,11 @@ def cvmousecb(self,event,x,y,flags,param): self.pe=None if event == cv.CV_EVENT_LBUTTONUP: #with self.extractionlck: - print 'add correspondence',x,y + print('add correspondence',x,y) self.imagepoints.append(array((x,y),float)) elif event == cv.CV_EVENT_RBUTTONUP: #with self.extractionlck: - print 'reset' + print('reset') self.imagepoints = [] self.pe=None def drawpart(self,cv_image,T,KK): @@ -355,13 +355,13 @@ def SetTemplateFn(self,req): template = {'type':self.type,'points3d':points3d,'descriptors':descriptors,'Itemplate':self.Itemplate,'boundingbox':self.boundingbox,'Tright':self.Tright,'featuretype':res.features.type} try: self.pe = PointPoseExtractor(type=self.type,points3d=points3d,descriptors=descriptors) - except detection_error,e: - print e + except detection_error as e: + print(e) self.pe=None if len(req.savefilename) > 0: pickle.dump(template,open(req.savefilename,'w')) - except (rospy.service.ServiceException,CvBridgeError),e: - print e + except (rospy.service.ServiceException,CvBridgeError) as e: + print(e) return None return SetTemplateResponse() @@ -374,8 +374,8 @@ def featureimagecb(self,featuremsg): with self.extractionlck: try: cv_image = self.bridge.imgmsg_to_cv(featuremsg.image, "bgr8") - except CvBridgeError, e: - print e + except CvBridgeError as e: + print(e) return # decompose P=KK*Tcamera P = reshape(array(featuremsg.info.P),(3,4)) @@ -386,13 +386,13 @@ def featureimagecb(self,featuremsg): KK = array(cvKK) Tcamera = eye(4) Tcamera[0:3,:] = c_[array(cvRcamera),-dot(array(cvRcamera),array(cvTcamera)[0:3]/cvTcamera[3,0])] - print "Tcamera: ",Tcamera + print("Tcamera: ",Tcamera) if self.pe is None: if len(self.imagepoints) >= 4: xaxis = self.imagepoints[1]-self.imagepoints[0] yaxis = self.imagepoints[2]-self.imagepoints[1] if xaxis[0]*yaxis[1]-xaxis[1]*yaxis[0] < 0: - print 'point order is not correct! need to specify points in clockwise order' + print('point order is not correct! need to specify points in clockwise order') self.imagepoints=[] return # find the homography, warp the image, and get new features @@ -421,8 +421,8 @@ def featureimagecb(self,featuremsg): scipy.misc.pilutil.imshow(self.Itemplate) self.pe = PointPoseExtractor(type=self.type,points3d=points3d,descriptors=descriptors) self.imagepoints = [] - except rospy.service.ServiceException,e: - print e + except rospy.service.ServiceException as e: + print(e) return else: success = False @@ -453,11 +453,11 @@ def featureimagecb(self,featuremsg): objdetmsg = posedetection_msgs.msg.ObjectDetection() objdetmsg.objects=[pose] objdetmsg.header = featuremsg.image.header - print 'local texture: ',repr(Tlocal) + print('local texture: ',repr(Tlocal)) self.pub_objdet.publish(objdetmsg) self.drawpart(cv_image,Tlocalobject,KK) self.drawcoordsys(cv_image,Tlocalobject,KK) - except detection_error,e: + except detection_error as e: pass if self.verboselevel > 0: rospy.loginfo('%s: %s, detection time: %fs, projerror %f < %f'%(self.type,'success' if success else 'failure',time.time()-starttime,projerror,self.errorthresh)) @@ -475,7 +475,7 @@ def CreateTemplateFn(type='',imagefilename='',Tright=eye(4),object_width=100,obj cv_texture = cv.LoadImageM(imagefilename) [width,height] = cv.GetSize(cv_texture) - print 'image:name=%s, width=%d hegit=%d, object:width=%f hegith=%f'%(imagefilename,width,height,object_width,object_height) + print('image:name=%s, width=%d hegit=%d, object:width=%f hegith=%f'%(imagefilename,width,height,object_width,object_height)) res=rospy.ServiceProxy('Feature0DDetect',posedetection_msgs.srv.Feature0DDetect)(image=CvBridge().cv_to_imgmsg(cv_texture)) N = len(res.features.positions)/2 @@ -534,7 +534,7 @@ def CreateTemplateFn(type='',imagefilename='',Tright=eye(4),object_width=100,obj try: processor = ROSPlanarPoseProcessor(templateppfilename=options.template,errorthresh=options.errorthresh,neighthresh=options.neighthresh,thresh=options.thresh,Tright=T,dminexpected=options.dminexpected,ransaciters=options.ransaciters,showgui=options.showgui,verboselevel=0 if options.quiet else 1,type=options.type) rospy.spin() - except KeyboardInterrupt, e: + except KeyboardInterrupt as e: pass def test(): diff --git a/posedetectiondb/src/PoseFromCorrespondences.py b/posedetectiondb/src/PoseFromCorrespondences.py index bf1c853f99..fa4f51175d 100755 --- a/posedetectiondb/src/PoseFromCorrespondences.py +++ b/posedetectiondb/src/PoseFromCorrespondences.py @@ -173,7 +173,7 @@ def camerainfocb(self,infomsg): with self.extractionlck: self.KK = reshape(infomsg.K,(3,3)) if any([f!=0 for f in infomsg.D]): - print 'Program does not support distorted images' + print('Program does not support distorted images') def imagecb(self,imagemsg): with self.extractionlck: @@ -190,7 +190,7 @@ def objectcb(self,objectmsg): def AddCorrespondence(self): with self.extractionlck: - print 'add correspondence' + print('add correspondence') # if self.frame_id: # base_frame_id = self.orbody.GetLinks()[0].GetName() # (trans,rot) = self.lookupTransform(base_frame_id, self.frame_id, rospy.Time(0)) @@ -200,27 +200,27 @@ def AddCorrespondence(self): Tpattern_inv = linalg.inv(self.pattern[0]) self.imagepoints.append(array(self.cvpoint)) self.objectpoints.append(array(self.orpoint)) - print 'total gathered points: %d'%len(self.imagepoints) + print('total gathered points: %d'%len(self.imagepoints)) if len(self.imagepoints) >= 4: - print array(self.imagepoints) - print array(self.objectpoints) - print self.pattern[0] + print(array(self.imagepoints)) + print(array(self.objectpoints)) + print(self.pattern[0]) Tcameraobject = FindExtrinsicCameraParams(array(self.imagepoints,float),array(self.objectpoints,float),self.KK) self.Tobjectrel = dot(Tpattern_inv,Tcameraobject) - print 'camera transform: ', Tcameraobject + print('camera transform: ', Tcameraobject) values = reshape(self.Tobjectrel[0:3,0:4],(12,)) - print "relative transform is: ",self.Tobjectrel + print("relative transform is: ",self.Tobjectrel) self.T_entry.insert(0, ' '.join(str(f) for f in values)) else: - print 'point data not initialized' + print('point data not initialized') def Reset(self): - print 'reset' + print('reset') self.imagepoints = [] self.objectpoints = [] self.Tobjectrel = None def Quit(self): - print 'quitting from gui' + print('quitting from gui') self.doquit = True self.main.quit() @@ -290,7 +290,7 @@ def keycb(self, char): if a==1: self.Tobjectrel[:3,:3]=dot(R,self.Tobjectrel[:3,:3]) self.Tobjectrel[:3,3]=self.Tobjectrel[:3,3]+mintranslation*T - print "relative: ",self.Tobjectrel + print("relative: ",self.Tobjectrel) def spin(self): while not rospy.is_shutdown() and not self.doquit: @@ -306,8 +306,8 @@ def spin(self): try: cv_image = self.bridge.imgmsg_to_cv(imagemsg, "bgr8") - except CvBridgeError, e: - print e + except CvBridgeError as e: + print(e) if Tpattern is not None: if Tobjectrel is not None: @@ -326,7 +326,7 @@ def spin(self): self.keycb(char) gtk.gdk.threads_leave() time.sleep(1.0) - print 'quitting spin' + print('quitting spin') if __name__== '__main__': parser = OptionParser(description='Estiamtes the pose of an openrave object by specifying manual correspondeces between the image and the openrave environment. If a separate ObjectDetection pattern is added, will publish the pose of the object with respect to the pattern.') @@ -350,5 +350,5 @@ def spin(self): if options.Tobjectrel is not None: processor.Tobjectrel = r_[reshape([float(s) for s in options.Tobjectrel.split()[0:12]],[3,4]),[[0,0,0,1]]] processor.spin() - except KeyboardInterrupt, e: + except KeyboardInterrupt as e: pass