OpenCV图像处理基础
1、显示图像
结果
代码如下(示例):
#include <opencv2/opencv.hpp> //头文件
using namespace cv; //包含cv命名空间
static void test() {
// 【1】读入一张图片,载入图像
Mat srcImage = imread("lena.jpg");
// 【2】显示载入的图片
imshow("【1、显示图像】", srcImage);
// 【3】等待任意按键按下
waitKey(0);
}
int main( )
{
test();
system("pause");
return 0;
}
2、图像腐蚀
结果:
代码如下(示例):
#include<opencv2/opencv.hpp>
#include<string>
using namespace cv;
static void test()
{
//载入原图
std::string path = "1.jpg";
Mat srcImage = imread(path);
//显示原图
imshow("【原图】腐蚀操作", srcImage);
//进行腐蚀操作
Mat element = getStructuringElement(MORPH_RECT, Size(15, 15));
Mat dstImage;
erode(srcImage, dstImage, element);
//显示效果图
imshow("【效果图】腐蚀操作", dstImage);
waitKey(0);
}
int main()
{
test();
system("pause");
return 0;
}
3、blur图像模糊
结果:
代码如下(示例):
#include <opencv2/opencv.hpp> //头文件
using namespace cv; //包含cv命名空间
static void test()
{
//【1】载入原始图
std::string path = "binary.bmp";
Mat srcImage = imread(path);
//【2】显示原始图
imshow("均值滤波【原图】", srcImage);
//【3】进行均值滤波操作
Mat dstImage;
blur(srcImage, dstImage, Size(7, 7));
//【4】显示效果图
imshow("均值滤波【效果图】", dstImage);
waitKey(0);
}
int main()
{
test();
system("pause");
return 0;
}
4、canny边缘检测
结果:
代码如下(示例):
#include <opencv2/opencv.hpp>
using namespace cv;
static int test()
{
//【0】载入原始图
std::string path = "F:/images/renwu1.jpg";
Mat srcImage = imread(path);
imshow("【原始图】Canny边缘检测", srcImage); //显示原始图
Mat dstImage, edge, grayImage; //参数定义
//【1】创建与src同类型和大小的矩阵(dst)
dstImage.create(srcImage.size(), srcImage.type());
//【2】将原图像转换为灰度图像
cvtColor(srcImage, grayImage, COLOR_BGR2GRAY);
//【3】先用使用 3x3内核来降噪
blur(grayImage, edge, Size(3, 3));
//【4】运行Canny算子
Canny(edge, edge, 3, 21, 3);
//【5】显示效果图
imshow("【效果图】Canny边缘检测", edge);
waitKey(0);
return 0;
}
int main()
{
test();
system("pause");
return 0;
}
5、播放视频
结果:
代码如下(示例):
#include<opencv2/opencv.hpp>
#include<string>
using namespace cv;
static void test()
{
//【1】读入视频
std::string path = "ludingji.mp4";
VideoCapture capture(path);
//【2】循环显示每一帧
while (1)
{
Mat frame;//定义一个Mat变量,用于存储每一帧的图像
capture >> frame; //读取当前帧
//若视频播放完成,退出循环
if (frame.empty())
break;
imshow("读取视频", frame); //显示当前帧
waitKey(30); //延时30ms
}
}
int main()
{
test();
system("pause");
return 0;
}
7、调用摄像头
结果:
代码如下(示例):
#include <opencv2\opencv.hpp>
using namespace cv;
static void test()
{
//【1】从摄像头读入视频
VideoCapture capture(0);
//【2】循环显示每一帧
while (1)
{
Mat frame; //定义一个Mat变量,用于存储每一帧的图像
capture >> frame; //读取当前帧
imshow("读取视频", frame); //显示当前帧
waitKey(30); //延时30ms
}
}
int main()
{
test();
system("pause");
return 0;
}
8、彩色目标跟踪
结果:
#include <opencv2\opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
// 描述:声明全局变量
Mat image;
bool backprojMode = false;
bool selectObject = false;
int trackObject = 0;
bool showHist = true;
Point origin;
Rect selection;
int vmin = 10, vmax = 256, smin = 30;
//----------【onMouse( )回调函数】----------
// 描述:鼠标操作回调
//------------------------------------------
static void onMouse(int event, int x, int y, int, void*)
{
if (selectObject)
{
selection.x = MIN(x, origin.x);
selection.y = MIN(y, origin.y);
selection.width = std::abs(x - origin.x);
selection.height = std::abs(y - origin.y);
selection &= Rect(0, 0, image.cols, image.rows);
}
switch (event)
{
case EVENT_LBUTTONDOWN:
origin = Point(x, y);
selection = Rect(x, y, 0, 0);
selectObject = true;
break;
case EVENT_LBUTTONUP:
selectObject = false;
if (selection.width > 0 && selection.height > 0)
trackObject = -1;
break;
}
}
static void ShowHelpText()
{
cout << "\n\n\t\t\t 当前使用的OpenCV版本为:" << CV_VERSION
<< "\n\n -------------------------------------------------------------";
cout << "\n\n\t此Demo显示了基于均值漂移的追踪(tracking)技术\n"
"\t请用鼠标框选一个有颜色的物体,对它进行追踪操作\n";
cout << "\n\n\t操作说明: \n"
"\t\t用鼠标框选对象来初始化跟踪\n"
"\t\tESC - 退出程序\n"
"\t\tc - 停止追踪\n"
"\t\tb - 开/关-投影视图\n"
"\t\th - 显示/隐藏-对象直方图\n"
"\t\tp - 暂停视频\n";
}
const char* keys =
{
"{1| | 0 | camera number}"
};
int main(int argc, const char** argv)
{
ShowHelpText();
VideoCapture cap;
Rect trackWindow;
int hsize = 16;
float hranges[] = { 0,180 };
const float* phranges = hranges;
cap.open(0);
if (!cap.isOpened())
{
cout << "不能初始化摄像头\n";
}
namedWindow("Histogram", 0);
namedWindow("CamShift Demo", 0);
setMouseCallback("CamShift Demo", onMouse, 0);
createTrackbar("Vmin", "CamShift Demo", &vmin, 256, 0);
createTrackbar("Vmax", "CamShift Demo", &vmax, 256, 0);
createTrackbar("Smin", "CamShift Demo", &smin, 256, 0);
Mat frame, hsv, hue, mask, hist, histimg = Mat::zeros(200, 320, CV_8UC3), backproj;
bool paused = false;
for (;;)
{
if (!paused)
{
cap >> frame;
if (frame.empty())
break;
}
frame.copyTo(image);
if (!paused)
{
cvtColor(image, hsv, COLOR_BGR2HSV);
if (trackObject)
{
int _vmin = vmin, _vmax = vmax;
inRange(hsv, Scalar(0, smin, MIN(_vmin, _vmax)),
Scalar(180, 256, MAX(_vmin, _vmax)), mask);
int ch[] = { 0, 0 };
hue.create(hsv.size(), hsv.depth());
mixChannels(&hsv, 1, &hue, 1, ch, 1);
if (trackObject < 0)
{
Mat roi(hue, selection), maskroi(mask, selection);
calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
normalize(hist, hist, 0, 255, NORM_MINMAX);
trackWindow = selection;
trackObject = 1;
histimg = Scalar::all(0);
int binW = histimg.cols / hsize;
Mat buf(1, hsize, CV_8UC3);
for (int i = 0; i < hsize; i++)
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180. / hsize), 255, 255);
cvtColor(buf, buf, COLOR_HSV2BGR);
for (int i = 0; i < hsize; i++)
{
int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows / 255);
rectangle(histimg, Point(i*binW, histimg.rows),
Point((i + 1)*binW, histimg.rows - val),
Scalar(buf.at<Vec3b>(i)), -1, 8);
}
}
calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
backproj &= mask;
RotatedRect trackBox = CamShift(backproj, trackWindow,
TermCriteria(TermCriteria::EPS | TermCriteria::COUNT, 10, 1));
if (trackWindow.area() <= 1)
{
int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5) / 6;
trackWindow = Rect(trackWindow.x - r, trackWindow.y - r,
trackWindow.x + r, trackWindow.y + r) &
Rect(0, 0, cols, rows);
}
if (backprojMode)
cvtColor(backproj, image, COLOR_GRAY2BGR);
ellipse(image, trackBox, Scalar(0, 0, 255), 3, LINE_AA);
}
}
else if (trackObject < 0)
paused = false;
if (selectObject && selection.width > 0 && selection.height > 0)
{
Mat roi(image, selection);
bitwise_not(roi, roi);
}
imshow("CamShift Demo", image);
imshow("Histogram", histimg);
char c = (char)waitKey(10);
if (c == 27)
break;
switch (c)
{
case 'b':
backprojMode = !backprojMode;
break;
case 'c':
trackObject = 0;
histimg = Scalar::all(0);
break;
case 'h':
showHist = !showHist;
if (!showHist)
destroyWindow("Histogram");
else
namedWindow("Histogram", 1);
break;
case 'p':
paused = !paused;
break;
default:
;
}
}
return 0;
}