请使用cvtColor()函数、resize函数、cv_bridge函数,给出ubantu系统下将ros仿真摄像头图像输出为灰度图并降低分辨率的.cpp文件,同时给出其编译方法
时间: 2024-05-10 21:16:49 浏览: 96
MFC图像处理系统,使用Opencv库,完成了图像的灰度变换、形态学操作、图像分割、图像滤波、边缘检测、人脸检测+源代码+文档说
下面是将ROS仿真摄像头图像输出为灰度图并降低分辨率的cpp代码:
```cpp
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <image_transport/image_transport.h>
const int WIDTH = 320;
const int HEIGHT = 240;
void imageCallback(const sensor_msgs::Image::ConstPtr& msg)
{
cv::Mat image;
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
cv::cvtColor(cv_ptr->image, image, CV_BGR2GRAY); // 将图像转为灰度图
cv::resize(image, image, cv::Size(WIDTH, HEIGHT)); // 降低分辨率
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
// 显示图像
cv::imshow("image", image);
cv::waitKey(1);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "camera_subscriber");
ros::NodeHandle nh;
cv::namedWindow("image");
image_transport::ImageTransport it(nh);
image_transport::Subscriber sub = it.subscribe("/camera/image_raw", 1, imageCallback);
ros::spin();
cv::destroyWindow("image");
return 0;
}
```
编译方法:
1. 在ROS工作空间的src目录下创建一个新的package:`catkin_create_pkg image_subscriber roscpp sensor_msgs cv_bridge image_transport opencv2`
2. 在package目录下创建一个新的cpp文件:`image_subscriber.cpp`
3. 在CMakeLists.txt中添加以下内容:
```cmake
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(image_subscriber src/image_subscriber.cpp)
target_link_libraries(image_subscriber ${OpenCV_LIBRARIES} ${catkin_LIBRARIES})
```
4. 在terminal中进入ROS工作空间的根目录,执行`catkin_make`命令进行编译
注:需将以上代码保存在`image_subscriber.cpp`文件中,并将其放置于`src`文件夹下。
阅读全文