//
// Session1to3.hpp
// FirstOpenCVDemo
//
// Created by Dylan on 2017/12/5.
// Copyright © 2017年 Dylan. All rights reserved.
//
#ifndef Session1to3_hpp
#define Session1to3_hpp
#include
#endif /* Session1to3_hpp */
#include
#include
#include
#include
//#include
//#include
//#include
//#include
using namespace cv;
using namespace std;
void imageHandle();
void videoHandle(int capType = CAP_ANY);
int application_trace();
int camShiftDemomain();
void loadPicture();
void createWindowsAndTraceBar();
void imwritePicture();
// 图像混合
void mixedPicture();
void imageToVideo();
//
// Session1to3.cpp
// FirstOpenCVDemo
//
// Created by Dylan on 2017/12/5.
// Copyright © 2017年 Dylan. All rights reserved.
//
#include "Session1to3.h"
#pragma mark - --Demo Showcase 示例展示--
string imgPath= "/Users/DylanXiao/Desktop/test.jpg";
// 图像的一些处理方法
void imageHandle()
{
Mat img = imread(imgPath,1);
imshow("image", img); //read original img
// 腐蚀 erode
Mat element = getStructuringElement(MORPH_RECT, Size(15,15));
Mat dstImage;
erode(img, dstImage, element);
imshow("腐蚀效果图", dstImage);
waitKey(0);
// 滤波 blur
Mat blurImg;
blur(img,blurImg,Size(8,8));
imshow("均值滤波【效果图】",blurImg);
waitKey(0);
// 转为灰度图像
Mat grayImg;
cvtColor(img, grayImg, COLOR_BGR2RGB);
imshow("Gray", grayImg);
waitKey(0);
// 转为灰度图像
cvtColor(img, grayImg, CV_BGR2GRAY);
imshow("Gray", grayImg);
waitKey(0);
Mat edge;
blur(grayImg, edge, Size(3,3)); // 使用3*3内核降噪
Canny(edge, edge, 3, 9,3); // 运行Canny算子
imshow("[效果图]Canny 边缘检测", edge);
waitKey(0);
}
// 视频、摄像头的处理方式
void videoHandle(int capType)
{
namedWindow("Capture",WINDOW_NORMAL);
//resizeWindow("Capture", 800, 600);
VideoCapture capture;
//capture.open(capType); // 可以将open的参数改为“xxx.avi”视频地址,即可以播放视频
capture.open("/Users/DylanXiao/Desktop/ImgToVideo.avi");
while(1){
Mat frame;
capture >> frame; // read current img
if (frame.empty())
break;
int newheight = 800/ (frame.size().width/(float)frame.size().height);
Size newsize= Size(800,newheight);
resize(frame, frame, newsize);
/*
cvtColor(frame, frame, COLOR_BGR2GRAY);
blur(frame, frame, Size(5,5));
Canny(frame, frame, 0, 30,3);
*/
imshow("Capture", frame); // show current image
waitKey(5); // Delay 30ms
}
}
int video_picture(string filename)
{
int i = 0;
int j = 0;
//读入视频
//VideoCapture capture(filename);
VideoCapture capture;
capture.open(0);
double rate = capture.get(CV_CAP_PROP_FPS); //获取视频帧率
//循环读取每一帧
while (1){
Mat frame; //Mat:存储每一帧的图像
capture >> frame; //读取当前帧
imshow("read", frame);
i++;
if (i == 6*rate){ //10fps/s 1min->600fps
i = 0;
j++;
//imshow("读取视频", frame); //显示当前帧
string name_1 = "/Users/DylanXiao/Desktop/image/testImageToVideo/";
string name_2 = to_string(j);
string name_3 = ".jpg";
name_1 += name_2;
name_1 += name_3; //图片存储路径及名字
if (!frame.empty()){
imwrite(name_1, frame);//截取当前帧并以图像的形式保存
waitKey(30); //延时30ms
}
if (frame.empty())
break;
}
if (cv::waitKey(30) == 27) //ESC:ASCⅡ码27
{
cout << "按下ESC键" << endl;
break;
}
}
waitKey();
return j;
}
void Image_To_Video(int p_num)
{
p_num=24;
char image_name[100];
string s_image_name;
//初始化视频编写器
cv::VideoWriter writer;
int isColor = 1; //true
int frame_fps = 10;
int frame_width = 1280;
int frame_height = 720;
using namespace cv;
string video_name = "/Users/DylanXiao/Desktop/ImgToVideo.avi"; //视频名字及路径
writer = VideoWriter(video_name, CV_FOURCC('X', 'V', 'I', 'D'), frame_fps, Size(frame_width, frame_height), isColor);
cv::namedWindow("image to video", CV_WINDOW_AUTOSIZE);
int i = 0;
Mat img;
while (i < p_num)
{
sprintf(image_name, "%s%d%s", "/Users/DylanXiao/Desktop/image/testImageToVideo/", ++i, ".jpg");
s_image_name = image_name;
img = imread(s_image_name);//读入图片
if (!img.data) //判断图片调入是否成功
{
cout << "Could not load image file...\n" << endl;
}
//非空判断
if (!img.empty())
{
imshow("image to video", img);
cout<<"Write "<": "<< s_image_name <
//写入
writer.write(img);
}
if (cv::waitKey(30) == 27) //ESC:ASCⅡ码27
{
cout << "按下ESC键" << endl;
break;
}
}
cout<<"Write over\n";
}
void imageToVideo()
{
int n = video_picture(""); // 截取帧
Image_To_Video(n); // 图像整合成视频
}
#pragma mark - CamshiftDemo
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;
// User draws box around object to track. This triggers CAMShift to start tracking
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; // Set up CAMShift properties in main() loop
break;
}
}
string hot_keys =
"\n\nHot keys: \n"
"\tESC - quit the program\n"
"\tc - stop the tracking\n"
"\tb - switch to/from backprojection view\n"
"\th - show/hide object histogram\n"
"\tp - pause video\n"
"To initialize tracking, select the object with mouse\n";
static void help()
{
cout << "\nThis is a demo that shows mean-shift based tracking\n"
"You select a color objects such as your face and it tracks it.\n"
"This reads from video camera (0 by default, or the camera number the user enters\n"
"Usage: \n"
" ./camshiftdemo [camera number]\n";
cout << hot_keys;
}
const char* keys =
{
"{help h | | show help message}{@camera_number| 0 | camera number}"
};
int camShiftDemomain()
{
VideoCapture cap;
Rect trackWindow;
int hsize = 16;
float hranges[] = {0,180};
const float* phranges = hranges;
cap.open(CAP_ANY);
if( !cap.isOpened() )
{
help();
cout << "***Could not initialize capturing...***\n";
cout << "Current parameter's value: \n";
return -1;
}
cout << hot_keys;
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 )
{
// Object has been selected by user, set up CAMShift search properties once
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; // Don't set up again, unless user selects new ROI
histimg = Scalar::all(0);
int binW = histimg.cols / hsize;
Mat buf(1, hsize, CV_8UC3);
for( int i = 0; i < hsize; i++ )
buf.at
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
}
}
// Perform CAMShift
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;
}
#pragma mark - Trace
static void process_frame(const cv::UMat& frame)
{
CV_TRACE_FUNCTION(); // OpenCV Trace macro for function
imshow("Live", frame);
UMat gray, processed;
cv::cvtColor(frame, gray, COLOR_BGR2GRAY);
Canny(gray, processed, 32, 64, 3);
imshow("Processed", processed);
}
int application_trace()
{
CV_TRACE_FUNCTION();
VideoCapture capture;
std::string video = "0";
if (video.size() == 1 && isdigit(video[0]))
capture.open(0);
else
capture.open(video);
int nframes = 0;
if (capture.isOpened())
{
nframes = (int)capture.get(CAP_PROP_FRAME_COUNT);
cout << "Video " << video <<
": width=" << capture.get(CAP_PROP_FRAME_WIDTH) <<
", height=" << capture.get(CAP_PROP_FRAME_HEIGHT) <<
", nframes=" << nframes << endl;
}
else
{
cout << "Could not initialize video capturing...\n";
return -1;
}
int N = 0;
if (nframes > 0 && N > nframes)
N = nframes;
cout << "Start processing..." << endl
<< "Press ESC key to terminate" << endl;
UMat frame;
for (int i = 0; N > 0 ? (i < N) : true; i++)
{
CV_TRACE_REGION("FRAME"); // OpenCV Trace macro for named "scope" region
{
CV_TRACE_REGION("read");
capture.read(frame);
if (frame.empty())
{
cerr << "Can't capture frame: " << i << std::endl;
break;
}
// OpenCV Trace macro for NEXT named region in the same C++ scope
// Previous "read" region will be marked complete on this line.
// Use this to eliminate unnecessary curly braces.
CV_TRACE_REGION_NEXT("process");
process_frame(frame);
CV_TRACE_REGION_NEXT("delay");
if (waitKey(1) == 27/*ESC*/)
break;
}
}
return 0;
}
#pragma mark - createWindow&TraceBar
void createWindowsAndTraceBar()
{
namedWindow("WindowDemo",WINDOW_NORMAL); // user can resize the window
createTrackbar("Process", "WindowDemo", &vmin, 400);
imshow("WindowDemo", 0);
waitKey();
// 载入三通道图像
Mat img = imread(imgPath,CV_LOAD_IMAGE_COLOR|CV_LOAD_IMAGE_ANYDEPTH);
imshow("WindowDemo", img);
waitKey();
}
#pragma mark - --OpenCV 入门基本操作--
void loadPicture()
{
imgPath ="/Users/DylanXiao/Desktop/OpenAlphaimage.png";
// 载入三通道图像
Mat img = imread(imgPath,CV_LOAD_IMAGE_COLOR|CV_LOAD_IMAGE_ANYDEPTH);
imshow("image", img); //read original img
waitKey();
// 载入无损的源图像
Mat img2 = imread(imgPath,CV_LOAD_IMAGE_ANYDEPTH|CV_LOAD_IMAGE_ANYCOLOR);
imshow("no lost original", img2);
waitKey();
}
void creatAlphaMat(Mat &mat)
{
for(int i = 0 ; i
{
for(int j=0;j
{
Vec4b &rgba = mat.at
rgba[0]=UCHAR_MAX;
rgba[1]=saturate_cast
rgba[2]=saturate_cast
rgba[3]=saturate_cast
}
}
}
// 保存图片
void imwritePicture()
{
Mat mat(480,640,CV_8UC(4));
creatAlphaMat(mat);
vector<int> compression_param;
// 这句代码是OpenCV2版
//compression_param.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_param.push_back(IMWRITE_PNG_COMPRESSION);
compression_param.push_back(9);
namedWindow("WindowDemo",WINDOW_NORMAL); // user can resize the window
try{
imwrite("/Users/DylanXiao/Desktop/OpenAlphaimage.png", mat,compression_param);
imshow("WindowDemo", mat);
fprintf(stdout, "alpha of imge save success.\nyou can see it in your project.\n");
waitKey(0);
}
catch(runtime_error &ex)
{
fprintf(stderr, "Format error:%s\n",ex.what());
}
}
//混合图片
void mixedPicture()
{
string imgPath1 = "/Users/DylanXiao/Desktop/image/test1.png";
string imgPath2 = "/Users/DylanXiao/Desktop/image/test2.png";
string imgPath3 = "/Users/DylanXiao/Desktop/image/test3.png";
//---------------------[一.图像的载入和显示]---------------------
Mat t1 = imread(imgPath1); // 载入图像到Mat
Mat t2 = imread(imgPath2);
Mat t3 = imread(imgPath3);
namedWindow("[1]img_test1"); // 创建相应的名称窗口
namedWindow("[1]img_test2",199);
namedWindow("[1]img_test3");
imshow("[1]img_test1", t1); // 显示名为 winname的窗口
imshow("[1]img_test2", t2); // 显示名为 winname的窗口
imshow("[1]img_test3", t3); // 显示名为 winname的窗口
image = t1;
///---------------------[二.图像初级混合]----------------------
// 定义一个Mat类型,用于存放图像的ROI
Mat imgROI;
// 方法一
imgROI = image(Rect(300,150,t2.cols,t2.rows));
// 方法二
//imgROI = image(Range(350,350+t2.rows),Range(800,800+t2.cols));
//将t2附加到t1上
addWeighted(imgROI, 0.5, t2, 0.3, 0., imgROI);
namedWindow("T2+image");
imshow("T2+image", image);
//---------------------[三.图像的输出保存]---------------------
imwrite("/Users/DylanXiao/Desktop/image/TestMixed.jpg",image);
waitKey();
}
#pragma mark - --Demo Showcase 示例展示--
// 边缘检测--opencv 1.0
IplImage* doCanny(IplImage* image_input,
double lowThresh,
double highThresh,
double aperture)
{
if(image_input->nChannels != 1)
return (0);
IplImage* image_output = cvCreateImage(cvGetSize(image_input),
image_input->depth,
image_input->nChannels);
cvCanny(image_input,image_output,lowThresh,highThresh,aperture);
return(image_output);
}
void getImageFromCamera()
{
cvNamedWindow("Camera" , CV_WINDOW_AUTOSIZE );
CvCapture* capture = cvCreateCameraCapture(CV_CAP_ANY);
assert(capture != NULL);
IplImage *frame = 0;
frame = cvQueryFrame(capture);
IplImage *frame_edge = cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U,1);
while(1)
{
frame = cvQueryFrame(capture);
if(!frame) break;
cvConvertImage(frame,frame_edge,0);
frame = cvCloneImage(frame_edge);
frame_edge = doCanny(frame_edge,70,90,3);
cvShowImage("Camera",frame_edge);
char c = cvWaitKey(15);
if(c == 27) break;
}
cvReleaseCapture(&capture);
cvReleaseImage( &frame_edge );
cvReleaseImage( &frame);
}