OPenCV C++
时间: 2023-11-14 20:06:35 浏览: 98
OpenCV是一个开源计算机视觉库,用于图像和视频处理。C++是OpenCV的主要编程语言,但也可以使用C进行开发。以下是使用C语言编写的一些OpenCV代码示例:
示例1:读取视频文件
```
#include <opencv2/opencv.hpp>
#include <stdio.h>
int main() {
CvCapture* capture;
IplImage* frame;
capture = cvCaptureFromFile("test_video.mp4");
cvNamedWindow("Video", CV_WINDOW_AUTOSIZE);
while (1) {
frame = cvQueryFrame(capture);
if (!frame) break;
cvShowImage("Video", frame);
char c = cvWaitKey(33);
if (c == 27) break;
}
cvReleaseCapture(&capture);
cvDestroyWindow("Video");
return 0;
}
```
这段代码使用了CvCapture和IplImage结构,通过cvCaptureFromFile函数从视频文件中读取帧,并使用cvShowImage函数显示每一帧。
示例2:读取摄像头
```
#include <opencv2/opencv.hpp>
#include <stdio.h>
int main() {
CvCapture* capture;
IplImage* frame;
capture = cvCaptureFromCAM(0);
cvNamedWindow("Video", CV_WINDOW_AUTOSIZE);
while (1) {
frame = cvQueryFrame(capture);
cvShowImage("Video", frame);
char c = cvWaitKey(33);
if (c == 27) break;
}
cvReleaseCapture(&capture);
cvDestroyWindow("Video");
return 0;
}
```
这段代码使用了cvCaptureFromCAM函数从摄像头中读取帧,并显示每一帧。
示例3:图像处理 - 绘制圆形
```
#include <opencv2/opencv.hpp>
#include <stdio.h>
int main() {
cv::Mat image = cv::Mat::zeros(300, 600, CV_8UC3);
cv::circle(image, cv::Point(300, 200), 100, cv::Scalar(25, 110, 288), -100);
cv::circle(image, cv::Point(400, 200), 100, cv::Scalar(255, 123, 127), -100);
cv::imshow("Image", image);
cv::waitKey(0);
return 0;
}
```
这段代码创建了一个黑色的图像,并使用cv::circle函数在图像上绘制了两个圆形。
示例4:对象检测
```
#include <opencv2/opencv.hpp>
#include <stdio.h>
int main() {
cv::Mat img = cv::imread("test.png");
cv::CascadeClassifier faceCascade;
faceCascade.load("haarcascade_frontalface_default.xml");
std::vector<cv::Rect> faces;
faceCascade.detectMultiScale(img, faces, 1.1, 10);
for (int i = 0; i < faces.size(); i++) {
cv::rectangle(img, faces[i].tl(), faces[i].br(), cv::Scalar(255, 0, 255), 3);
}
cv::imshow("Image", img);
cv::waitKey(0);
return 0;
}
```
这段代码使用cv::CascadeClassifier类加载了一个面部识别的级联分类器,并在输入图像中检测到的面部周围绘制了矩形框。
希望这些示例代码对您有所帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [OpenCV入门【C++版】](https://blog.csdn.net/Star_ID/article/details/122656593)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* [OpenCV安装及其开发环境配置(C++)](https://blog.csdn.net/m0_61897853/article/details/122609454)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文