00001 #include <ros/ros.h> 00002 #include <ros/node_handle.h> 00003 #include "sensor_msgs/Image.h" 00004 #include "image_transport/image_transport.h" 00005 #include "cv_bridge/CvBridge.h" 00006 #include <opencv/cv.h> 00007 #include <opencv/highgui.h> 00008 #include <string.h> 00009 using namespace std; 00010 00011 class ImageConverter { 00012 00013 public: 00014 string image_file_; 00015 IplImage *cv_image_; 00016 double rate_; 00017 ImageConverter(ros::NodeHandle &n) : 00018 n_(n), it_(n_) 00019 { 00020 image_pub_ = it_.advertise("image_topic_2",50); 00021 } 00022 00023 00024 ~ImageConverter() 00025 { 00026 } 00027 00029 // Spin (!) 00030 bool spin () 00031 { 00032 //double interval = rate_ * 1e+6; 00033 ros::Rate loop_rate(rate_); 00034 while (n_.ok ()) 00035 { 00036 ROS_INFO ("Publishing data on topic %s.", n_.resolveName ("image_topic_2").c_str ()); 00037 try 00038 { 00039 image_pub_.publish(bridge_.cvToImgMsg(cv_image_)); 00040 } 00041 catch (sensor_msgs::CvBridgeException error) 00042 { 00043 ROS_ERROR("Error converting image"); 00044 } 00045 00046 if (rate_ == 0) 00047 break; 00048 loop_rate.sleep(); 00049 ros::spinOnce (); 00050 } 00051 return (true); 00052 } 00053 00054 protected: 00055 00056 ros::NodeHandle n_; 00057 image_transport::ImageTransport it_; 00058 sensor_msgs::CvBridge bridge_; 00059 image_transport::Publisher image_pub_; 00060 00061 }; 00062 00063 int main(int argc, char** argv) 00064 { 00065 if (argc < 3) 00066 { 00067 ROS_ERROR ("Syntax is: %s <image file> [publishing_rate (in Hz)]", argv[0]); 00068 return (-1); 00069 } 00070 ros::init(argc, argv, "openCv_to_ros"); 00071 ros::NodeHandle n; 00072 ImageConverter ic(n); 00073 ic.image_file_ = string(argv[1]); 00074 ic.rate_ = atof (argv[2]); 00075 ROS_INFO ("Loading file %s...", ic.image_file_.c_str ()); 00076 ic.cv_image_ = cvLoadImage(ic.image_file_.c_str(), 1); 00077 // if (ic.cv_image_->width > 60 && ic.cv_image_->height > 60) 00078 // cvCircle(ic.cv_image_, cvPoint(50,50), 10, CV_RGB( 0, 255, 0 ), 5); 00079 ic.spin(); 00080 return 0; 00081 }