pickup_red / data_collection.py
luna-shi's picture
Upload 43 files
ba72f6d verified
# -*- coding: utf-8 -*-
import rospy
import cv2
import os
import time
from sensor_msgs.msg import JointState, Image
from cv_bridge import CvBridge
# �Զ������ݽṹ
class DataCollection:
def __init__(self):
self.joint_states = None
self.image = None
self.joint_states_frame_id = None
self.image_frame_id = None
# ȫ�ֱ���
data_collection = DataCollection()
bridge = CvBridge()
frame_id = 0
# �������
def create_data_folder():
# ��ȡ��ǰʱ�䣬��ʽΪYYYYMMDD_HHMMSS
current_time = time.strftime("%Y%m%d_%H%M%S")
folder_name = f"{current_time}_data"
# �������
os.makedirs(folder_name, exist_ok=True)
return folder_name
def joint_states_callback(msg):
global data_collection,frame_id
data_collection.joint_states = msg.position
data_collection.joint_states_frame_id = frame_id
def image_callback(msg):
global data_collection,frame_id
try:
# ��ROSͼ����Ϣת��ΪOpenCVͼ��
cv_image = bridge.imgmsg_to_cv2(msg, "bgr8")
data_collection.image = cv_image
data_collection.image_frame_id = frame_id
except Exception as e:
rospy.logerr(e)
def collect_data(folder_path):
global data_collection,frame_id
fps = 10
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Codec for MP4
out = cv2.VideoWriter(os.path.join(folder_path, f"out.mp4"), fourcc, fps, (640, 480)) # Adjust resolutio
rate = rospy.Rate(10) # 10Hz
while not rospy.is_shutdown():
if data_collection.joint_states is not None and data_collection.image is not None:
# �������ݵ��ļ�
timestamp = time.strftime("%Y%m%d-%H%M%S")
joint_states_filename = os.path.join(folder_path, f"joint_states.txt")
image_filename = os.path.join(folder_path, f"image_{timestamp}.png")
# ����JointStates
with open(joint_states_filename, 'a') as f:
f.write(f"Frame ID: {data_collection.joint_states_frame_id}\n")
f.write(f"Joint Positions: {data_collection.joint_states}\n")
# ����ͼ��
out.write(data_collection.image)
frame_id += 1
rospy.loginfo(f"Data saved to {joint_states_filename} and {image_filename}")
# ��������
data_collection = DataCollection()
rate.sleep()
if __name__ == '__main__':
rospy.init_node('data_collection_node', anonymous=True)
# �������
folder_path = create_data_folder()
rospy.loginfo(f"Data will be saved to: {folder_path}")
# ������
rospy.Subscriber("/Arm_2_JointStates", JointState, joint_states_callback)
rospy.Subscriber("/usb_cam/image_raw", Image, image_callback)
# ��ʼ�ռ�����
collect_data(folder_path)