ubuntu22.04@laptop OpenCV Get Started: 013_contour_detection
1. 源由
使用轮廓检测检测物体的边界,通常是许多有趣应用的第一步,如图像前景提取、简单的图像分割、检测和识别。
罗列一些使用轮廓进行运动检测或分割应用:
- 运动检测:在监控视频中,运动检测技术有许多应用,包括室内和室外安全环境、交通控制、体育活动中的行为检测、无人看管物体的检测,甚至视频压缩。在下图中,可以看到检测视频流中的人员移动在监控应用程序中是如何有用的。请注意,未检测到静止在图像左侧的那组人。只有运动中的人才会被捕捉到。请参考《Moving Object Detection and Segmentation using Frame differencing and Summing Technique》详细研究这种方法。
- 无人值守物体检测:公共场所的无人值守物体通常被视为可疑物体。一个有效且安全的解决方案详见:《Unattended Object Detection through Contour Formation using Background Subtraction》。
- 背景/前景分割:要用另一个图像替换图像的背景,需要执行图像前景提取(类似于图像分割)。使用轮廓是可以用于执行分割的一种方法。有关更多详细信息,请参阅《Background Removal with Python Using OpenCV to Detect the Foreground》。
2. 应用Demo
013_contour_detection是OpenCV通过鼠标指针和轨迹条与用户交互的示例。
2.1 C++应用Demo
C++应用Demo工程结构:
013_contour_detection/CPP$ tree . .
├── channel_experiments
│ ├── channel_experiments.cpp
│ └── CMakeLists.txt
├── contour_approximations
│ ├── CMakeLists.txt
│ └── contour_approx.cpp
└── contour_extraction
├── CMakeLists.txt
└── contour_extraction.cpp
3 directories, 6 files
确认OpenCV安装路径:
$ find /home/daniel/ -name "OpenCVConfig.cmake"
/home/daniel/OpenCV/installation/opencv-4.9.0/lib/cmake/opencv4/
/home/daniel/OpenCV/opencv/build/OpenCVConfig.cmake
/home/daniel/OpenCV/opencv/build/unix-install/OpenCVConfig.cmake
$ export OpenCV_DIR=/home/daniel/OpenCV/installation/opencv-4.9.0/lib/cmake/opencv4/
C++应用Demo工程编译执行:
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
$ cd ..
$ ./build/channel_experiments
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
$ cd ..
$ ./build/contour_approximations
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
$ cd ..
$ ./build/contour_extraction
2.2 Python应用Demo
Python应用Demo工程结构:
013_contour_detection/Python$ tree .
.
├── channel_experiments
│ └── channel_experiments.py
├── contour_approximations
│ └── contour_approx.py
├── contour_extraction
│ └── contour_extraction.py
└── requirements.txt
3 directories, 4 files
Python应用Demo工程执行:
$ workoncv-4.9.0
$ python channel_experiments.py
$ python contour_approx.py
$ python contour_extraction.py
3. contour_approx应用
在OpenCV中检测和绘制轮廓的步骤如下所示:
- 读取图像并将其转换为灰度格式
- 应用二进制阈值过滤算法
- 查找对象轮廓
- 绘制对象轮廓
查找轮廓可以采用两种方式:
- CHAIN_APPROX_SIMPLE
- CHAIN_APPROX_NONE
3.1 读取图像并将其转换为灰度格式
读取图像并将图像转换为灰度格式。将图像转换为灰度非常重要,因为它为下一步的图像做准备。
将图像转换为单通道灰度图像对于阈值处理很重要,这反过来又是轮廓检测算法正常工作所必需的。
C++:
// read the image
Mat image = imread("../../input/image_1.jpg");
// convert the image to grayscale format
Mat img_gray;
cvtColor(image, img_gray, COLOR_BGR2GRAY);
Python:<