Opencv学习2:指定图像读取

  此次图像读取学习,所有程序都是在opencv_learning功能包下编译完成的。

创建功能包opencv_learning

创建功能包

  打开终端,创建功能包opencv_learning

$ cs
$ catkin_create_pkg opencv_learning std_msgs roscpp rospy cv_bridge image_transport sensor_msgs
$ cm

添加OpenCV库

  修改功能包下CMakeLists.txt文件

CMakeLists.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
find_package(catkin REQUIRED COMPONENTS
+ OpenCV
cv_bridge
image_transport
sensor_msgs
std_msgs
roscpp
rospy
)

include_directories(
include ${catkin_INCLUDE_DIRS}
# include
${catkin_INCLUDE_DIRS}
+ ${OpenCV_INCLUDE_DIRS}
)

读取指定图片

添加图片

图片路径:/home/tao/opencv/1.jpg

1.jpg

c++程序

  • 新建程序
read_image_c.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <ros/ros.h>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

int main(int argc, char** argv)
{
//创建一个Mat对象cv_image,它将存储加载的图像的数据
cv::Mat cv_image = cv::imread("/home/tao/opencv/1.jpg");
if(cv_image.empty())
{
ROS_ERROR("Read the picture failed!");
return -1;
}
//创建窗口,显示图像
cv::namedWindow("Display Image",cv::WINDOW_NORMAL);
cv::resizeWindow("Display Image", 640, 480);
cv::imshow("Display Image", cv_image);
cv::waitKey(0);
cv::destroyAllWindows();

return 0;
}
  • 修改功能包下CMakeLists.txt文件,添加以下内容
CMakeLists.txt
1
2
3
4
5
6
7
add_executable(read_image_c
src/read_image_c.cpp
)
add_dependencies(read_image_c ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(read_image_c
${catkin_LIBRARIES}
)
  • 编译运行
$ cm
$ rosrun opencv_learning read_image_c
c++程序运行结果

python程序

read_image_p.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python2
# coding:utf-8

import rospy
import cv2

def read_image():
img = cv2.imread('/home/tao/opencv/1.jpg',cv2.IMREAD_COLOR)
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
cv2.resizeWindow("image", 640, 480);
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

if __name__ == '__main__':
read_image()
  • 添加权限并运行
$ cs
$ cd opencv_learning/src/
$ chmod +x read_image_p.py 
$ rosrun opencv_learning read_image_p.py
python程序运行结果
+