ROS opencv
2024. 4. 17. 21:07ㆍROS
sudo apt-get install ros-noetic-opencv*
sudo apt-get install ros-noetic-usb-cam
sudo apt-get install ros-noetic-cv-bridge
sudo apt-get install ros-noetic-cv-camera
cd ~/catkin_ws/src
catkin_create_pkg ros_opencv message_generation cv_bridge image_transform sensor_msgs roscpp serial std_msgs
//ros_opencv_pub
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <image_transport/image_transport.h>
#include <iostream>
#include <vector>
#include <ros/ros.h>
#include <opencv2/highgui/highgui.hpp>
#include <std_msgs/UInt8MultiArray.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "opencv_pub");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<std_msgs::UInt8MultiArray>("camera/image", 1);
cv::VideoCapture cap(0);
cv::Mat frame;
while(nh.ok())
{
cap >> frame;
if(!frame.empty())
{
cv::imshow("frame", frame);
// Encode, Decode image example
std::vector<uchar> encode;
std::vector<int> encode_param;
encode_param.push_back(cv::IMWRITE_JPEG_QUALITY);
encode_param.push_back(20);
cv::imencode(".jpg", frame, encode, encode_param);
cv::Mat decode = cv::imdecode(encode, 1);
cv::imshow("decode", decode);
// Convert encoded image to ROS std_msgs format
std_msgs::UInt8MultiArray msgArray;
msgArray.data.clear();
msgArray.data.resize(encode.size());
std::copy(encode.begin(), encode.end(), msgArray.data.begin());
// Publish msg
pub.publish(msgArray);
cv::waitKey(1);
}
ros::spinOnce();
}
return 0;
}
//ros_opencv_sub
#include <ros/ros.h>
#include <opencv2/opencv.hpp>
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>
#include <vector>
#include <std_msgs/UInt8MultiArray.h>
void imageCallback(const std_msgs::UInt8MultiArray::ConstPtr& array)
{
try
{
cv::Mat frame = cv::imdecode(array->data, 1);
cv::imshow("view", frame);
cv::waitKey(1);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cannot decode image");
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "opencv_sub");
cv::namedWindow("view");
cv::startWindowThread();
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("camera/image", 5, imageCallback);
ros::spin();
cv::destroyWindow("view");
}
'ROS' 카테고리의 다른 글
ROS roslaunch (0) | 2024.04.17 |
---|---|
ROS 파라미터 (0) | 2024.04.17 |
ROS 서비스 (0) | 2024.04.17 |
ROS 토픽 (0) | 2024.04.08 |
ROS 기본(20.04) (0) | 2024.04.02 |