ladybug.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <stdexcept>
  5. #include <unistd.h>
  6. #include <signal.h>
  7. #include <stdlib.h>
  8. #include <ros/ros.h>
  9. #include <sensor_msgs/image_encodings.h>
  10. #include <sensor_msgs/Image.h>
  11. #include <sensor_msgs/CameraInfo.h>
  12. #include <tf/transform_broadcaster.h>
  13. #include <tf/transform_datatypes.h>
  14. #include "opencv2/core/core.hpp"
  15. #include "opencv2/highgui/highgui.hpp"
  16. #include <opencv2/imgproc/imgproc.hpp>
  17. #include "ladybug.h"
  18. #include "ladybugstream.h"
  19. using namespace std;
  20. static volatile int running_ = 1;
  21. LadybugContext m_context;
  22. LadybugDataFormat m_dataFormat;
  23. //camera config settings
  24. float m_frameRate;
  25. bool m_isFrameRateAuto;
  26. unsigned int m_jpegQualityPercentage;
  27. ros::Publisher pub[LADYBUG_NUM_CAMERAS + 1];
  28. static void signalHandler(int)
  29. {
  30. running_ = 0;
  31. ros::shutdown();
  32. }
  33. void parseCameraInfo(const cv::Mat &camMat,
  34. const cv::Mat &disCoeff,
  35. const cv::Size &imgSize,
  36. sensor_msgs::CameraInfo &msg)
  37. {
  38. msg.header.frame_id = "camera";
  39. msg.height = imgSize.height;
  40. msg.width = imgSize.width;
  41. for (int row=0; row<3; row++)
  42. {
  43. for (int col=0; col<3; col++)
  44. {
  45. msg.K[row * 3 + col] = camMat.at<double>(row, col);
  46. }
  47. }
  48. for (int row=0; row<3; row++)
  49. {
  50. for (int col=0; col<4; col++)
  51. {
  52. if (col == 3)
  53. {
  54. msg.P[row * 4 + col] = 0.0f;
  55. } else
  56. {
  57. msg.P[row * 4 + col] = camMat.at<double>(row, col);
  58. }
  59. }
  60. }
  61. for (int row=0; row<disCoeff.rows; row++)
  62. {
  63. for (int col=0; col<disCoeff.cols; col++)
  64. {
  65. msg.D.push_back(disCoeff.at<double>(row, col));
  66. }
  67. }
  68. }
  69. void GetMatricesFromFile(ros::NodeHandle nh, sensor_msgs::CameraInfo &camerainfo_msg)
  70. {
  71. //////////////////CAMERA INFO/////////////////////////////////////////
  72. cv::Mat cameraExtrinsicMat;
  73. cv::Mat cameraMat;
  74. cv::Mat distCoeff;
  75. cv::Size imageSize;
  76. std::string filename;
  77. if (nh.getParam("calibrationfile", filename) && filename!="")
  78. {
  79. ROS_INFO("Trying to parse calibrationfile :");
  80. ROS_INFO("> %s", filename.c_str());
  81. }
  82. else
  83. {
  84. ROS_INFO("No calibrationfile param was received");
  85. return;
  86. }
  87. cv::FileStorage fs(filename, cv::FileStorage::READ);
  88. if (!fs.isOpened())
  89. {
  90. ROS_INFO("Cannot open %s", filename.c_str());;
  91. return;
  92. }
  93. else
  94. {
  95. fs["CameraMat"] >> cameraMat;
  96. fs["DistCoeff"] >> distCoeff;
  97. fs["ImageSize"] >> imageSize;
  98. }
  99. parseCameraInfo(cameraMat, distCoeff, imageSize, camerainfo_msg);
  100. }
  101. void publishImage(cv::Mat& image, ros::Publisher& image_pub, long int& count, size_t camera_id)
  102. {
  103. sensor_msgs::Image msg;
  104. //publish*******************
  105. msg.header.seq = count;
  106. std::string frame = "camera" + std::to_string(camera_id);
  107. msg.header.frame_id = frame;
  108. msg.header.stamp.sec = ros::Time::now().sec; msg.header.stamp.nsec = ros::Time::now().nsec;
  109. msg.height = image.size().height; msg.width = image.size().width;
  110. msg.encoding = "rgb8";
  111. msg.step = image.cols * image.elemSize();
  112. size_t image_size = image.rows * image.cols * image.elemSize();
  113. msg.data.resize(image_size);
  114. memcpy(msg.data.data(), image.data, image_size);
  115. image_pub.publish(msg);
  116. }
  117. LadybugError init_camera()
  118. {
  119. LadybugError error;
  120. error = ladybugCreateContext(&m_context);
  121. if (error != LADYBUG_OK)
  122. {
  123. throw std::runtime_error("Unable to create Ladybug context.");
  124. }
  125. LadybugCameraInfo enumeratedCameras[16];
  126. unsigned int numCameras = 16;
  127. error = ladybugBusEnumerateCameras(m_context, enumeratedCameras, &numCameras);
  128. if (error != LADYBUG_OK)
  129. {
  130. return error;
  131. }
  132. cout << "Cameras detected: " << numCameras << endl << endl;
  133. if (numCameras == 0)
  134. {
  135. ROS_INFO("Insufficient number of cameras detected. ");
  136. return LADYBUG_FAILED;
  137. }
  138. error = ladybugInitializeFromIndex(m_context, 0);
  139. if (error != LADYBUG_OK)
  140. {
  141. return error;
  142. }
  143. LadybugCameraInfo camInfo;
  144. error = ladybugGetCameraInfo(m_context, &camInfo);
  145. if (error != LADYBUG_OK)
  146. {
  147. return error;
  148. }
  149. ROS_INFO("Camera information: ");
  150. ROS_INFO("Base s/n: %d", camInfo.serialBase );
  151. ROS_INFO("Head s/n: %d", camInfo.serialHead );
  152. ROS_INFO("Model: %s", camInfo.pszModelName );
  153. ROS_INFO("Sensor: %s", camInfo.pszSensorInfo);
  154. ROS_INFO("Vendor: %s", camInfo.pszVendorName);
  155. ROS_INFO("Bus / Node: %d ,%d" , camInfo.iBusNum , camInfo.iNodeNum );
  156. switch (camInfo.deviceType)
  157. {
  158. case LADYBUG_DEVICE_LADYBUG3:
  159. {
  160. m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
  161. m_frameRate = 16.0f;
  162. m_isFrameRateAuto = true;
  163. m_jpegQualityPercentage = 80;
  164. }
  165. break;
  166. case LADYBUG_DEVICE_LADYBUG5:
  167. {
  168. m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
  169. m_frameRate = 10.0f;
  170. m_isFrameRateAuto = true;
  171. m_jpegQualityPercentage = 80;
  172. }
  173. break;
  174. default: assert(false); break;
  175. }
  176. return error;
  177. }
  178. LadybugError start_camera()
  179. {
  180. LadybugError error;
  181. error = ladybugStartLockNext(m_context, m_dataFormat);
  182. if (error != LADYBUG_OK)
  183. {
  184. return error;
  185. }
  186. error = ladybugSetAbsPropertyEx(m_context, LADYBUG_FRAME_RATE, false, true, m_isFrameRateAuto, m_frameRate);
  187. if (error != LADYBUG_OK)
  188. {
  189. return error;
  190. }
  191. error = ladybugSetJPEGQuality(m_context, m_jpegQualityPercentage);
  192. if (error != LADYBUG_OK)
  193. {
  194. return error;
  195. }
  196. // Perform a quick test to make sure images can be successfully acquired
  197. for (int i=0; i < 10; i++)
  198. {
  199. LadybugImage tempImage;
  200. error = ladybugLockNext(m_context, &tempImage);
  201. }
  202. error = ladybugUnlockAll(m_context);
  203. if (error != LADYBUG_OK)
  204. {
  205. return error;
  206. }
  207. return error;
  208. }
  209. LadybugError stop_camera()
  210. {
  211. const LadybugError cameraError = ladybugStop(m_context);
  212. if (cameraError != LADYBUG_OK)
  213. {
  214. ROS_INFO("Error: Unable to stop camera (%s)", ladybugErrorToString(cameraError) );
  215. }
  216. return cameraError;
  217. }
  218. LadybugError acquire_image( LadybugImage& image )
  219. {
  220. return ladybugLockNext(m_context, &image);
  221. }
  222. LadybugError unlock_image( unsigned int bufferIndex )
  223. {
  224. return ladybugUnlock(m_context, bufferIndex);
  225. }
  226. int main (int argc, char **argv)
  227. {
  228. ////ROS STUFF
  229. ros::init(argc, argv, "ladybug_camera");
  230. ros::NodeHandle n;
  231. ros::NodeHandle private_nh("~");
  232. signal(SIGTERM, signalHandler);//detect closing
  233. /////////////////////////////
  234. //Config camera
  235. m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
  236. m_frameRate = 10;
  237. m_isFrameRateAuto = true;
  238. m_jpegQualityPercentage = 80;
  239. // Initialize ladybug camera
  240. const LadybugError grabberInitError = init_camera();
  241. if (LADYBUG_OK != init_camera())
  242. {
  243. ROS_INFO("Error: Failed to initialize camera (%s). Terminating...", ladybugErrorToString(grabberInitError) );
  244. return -1;
  245. }
  246. LadybugCameraInfo camInfo;
  247. if (LADYBUG_OK != ladybugGetCameraInfo(m_context, &camInfo))
  248. {
  249. ROS_INFO("Error: Failed to get camera information. Terminating...");
  250. return -1;
  251. }
  252. const LadybugError startError = start_camera();
  253. if (startError != LADYBUG_OK)
  254. {
  255. ROS_INFO("Error: Failed to start camera (%s). Terminating...", ladybugErrorToString(startError) );
  256. return -1;
  257. }
  258. /////////////////////
  259. //ROS
  260. // Get the camera information
  261. ///////calibration data
  262. sensor_msgs::CameraInfo camerainfo_msg;
  263. GetMatricesFromFile(private_nh, camerainfo_msg);
  264. int image_scale = 100;
  265. if (private_nh.getParam("scale", image_scale) && image_scale>0 && image_scale<100)
  266. {
  267. ROS_INFO("Ladybug ImageScale > %i%%", image_scale);
  268. }
  269. else
  270. {
  271. ROS_INFO("Ladybug ImageScale scale must be (0,100]. Defaulting to 20 ");
  272. image_scale=20;
  273. }
  274. ros::Publisher camera_info_pub;
  275. camera_info_pub = n.advertise<sensor_msgs::CameraInfo>("/camera/camera_info", 1, true);
  276. ROS_INFO("Successfully started ladybug camera and stream");
  277. for (int i = 0; i < LADYBUG_NUM_CAMERAS + 1; i++) {
  278. std::string topic(std::string("image_raw"));
  279. topic = "camera" + std::to_string(i) + "/" + topic;
  280. pub[i] = n.advertise<sensor_msgs::Image>(topic, 100);
  281. ROS_INFO("Publishing.. %s", topic.c_str());
  282. }
  283. //////////////////
  284. //start camera
  285. ros::Rate loop_rate(10); // Hz Ladybug works at 10fps
  286. long int count = 0;
  287. while (running_ && ros::ok())
  288. {
  289. LadybugImage currentImage;
  290. const LadybugError acquisitionError = acquire_image(currentImage);
  291. if (acquisitionError != LADYBUG_OK)
  292. {
  293. ROS_INFO("Failed to acquire image. Error (%s). Trying to continue..", ladybugErrorToString(acquisitionError) );
  294. continue;
  295. }
  296. // convert to OpenCV Mat
  297. //receive Bayer Image, convert to Color 3 channels
  298. cv::Size size(currentImage.uiFullCols, currentImage.uiFullRows);
  299. cv::Mat full_size;
  300. for(size_t i =0;i<LADYBUG_NUM_CAMERAS; i++)
  301. {
  302. std::ostringstream out;
  303. out << "image" << i;
  304. cv::Mat rawImage(size, CV_8UC1, currentImage.pData + (i * size.width*size.height));
  305. cv::Mat image(size, CV_8UC3);
  306. cv::cvtColor(rawImage, image, cv::COLOR_BayerBG2RGB);
  307. cv::resize(image,image,cv::Size(size.width*image_scale/100, size.height*image_scale/100));
  308. //
  309. cv::transpose(image, image);
  310. cv::flip(image, image, 1);
  311. if (i==0)
  312. image.copyTo(full_size);
  313. else
  314. cv::hconcat(image, full_size, full_size);
  315. unlock_image(currentImage.uiBufferIndex);
  316. publishImage(image, pub[LADYBUG_NUM_CAMERAS - i], count, LADYBUG_NUM_CAMERAS - i);
  317. }
  318. //publish stitched one
  319. publishImage(full_size, pub[0], count, LADYBUG_NUM_CAMERAS);
  320. ros::spinOnce();
  321. loop_rate.sleep();
  322. count++;
  323. }
  324. cout << "Stopping ladybug_camera..." << endl;
  325. // Shutdown
  326. stop_camera();
  327. ROS_INFO("ladybug_camera stopped");
  328. return 0;
  329. }