如何将Android端ORB生成的关键点JSON转为Python的MatOfKeyPoint
Convert Android ORB Keypoint JSON to Python's MatOfKeyPoint
Got it, let's walk through how to turn that JSON string from your Android app into a proper cv2.MatOfKeyPoint object in Python. This relies on OpenCV's Python bindings and the built-in json module—here's a straightforward implementation:
Step 1: Set Up Dependencies
First, make sure you have the required packages installed:
pip install opencv-python
Step 2: Full Conversion Code
Here's the complete code that parses the JSON, builds individual cv2.KeyPoint instances, and wraps them into a MatOfKeyPoint:
import json import cv2 def json_to_mat_of_keypoints(json_str): # Parse the JSON string into a list of dictionaries keypoint_dicts = json.loads(json_str) # Create a list to hold cv2.KeyPoint objects keypoints_list = [] for kp_data in keypoint_dicts: # Map each JSON field to the cv2.KeyPoint constructor parameters # The order matches OpenCV's KeyPoint signature: x, y, size, angle, response, octave, class_id kp = cv2.KeyPoint( x=kp_data["x"], y=kp_data["y"], size=kp_data["size"], angle=kp_data["angle"], response=kp_data["response"], octave=kp_data["octave"], class_id=kp_data["class_id"] ) keypoints_list.append(kp) # Convert the list of KeyPoints to MatOfKeyPoint mat_kp = cv2.MatOfKeyPoint() mat_kp.fromList(keypoints_list) return mat_kp # Example usage with your sample JSON sample_json = '[{"class_id":-1,"x":208.0,"y":2492.0,"size":31.0,"angle":312.0059,"octave":0,"response":1.2840814E-4}, {"class_id":-1,"x":114.0,"y":1898.0,"size":31.0,"angle":312.86102,"octave":0,"response":1.4190769E-4}]' result_mat = json_to_mat_of_keypoints(sample_json) # Verify the conversion (optional) print(f"Number of keypoints in MatOfKeyPoint: {len(result_mat.toList())}")
Key Notes & Edge Cases
- Field Safety: If your JSON might have missing fields (e.g., some keypoints omit
angle), usekp_data.get("angle", -1.0)instead of direct indexing to avoidKeyErrorexceptions. - Float Compatibility: Android's scientific notation (like
1.2840814E-4) is automatically parsed to Python floats by thejsonmodule—no extra work needed. - OpenCV Version: Make sure your
opencv-pythonversion is compatible (most recent 4.x versions work seamlessly).
内容的提问来源于stack exchange,提问作者Pradeepta Ranjan Choudhury
相关产品推荐
相关产品推荐

