OpenCV 4.12.0
開源計算機視覺
載入中...
搜尋中...
無匹配項
samples/cpp/camshiftdemo.cpp

一個使用均值漂移跟蹤演算法的示例

#include <iostream>
#include <ctype.h>
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;
// 使用者圍繞要跟蹤的物件繪製框。這會觸發 CAMShift 開始跟蹤
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; // 在 main() 迴圈中設定 CAMShift 屬性
break;
}
}
string hot_keys =
"\n\n快捷鍵:\n"
"\tESC - 退出程式\n"
"\tc - 停止跟蹤\n"
"\tb - 切換到/退出反向投影檢視\n"
"\th - 顯示/隱藏物件直方圖\n"
"\tp - 暫停影片\n"
"要初始化跟蹤,請用滑鼠選擇物件\n";
static void help(const char** argv)
{
cout << "\n這是一個演示,展示了基於均值漂移的跟蹤\n"
"您可以選擇一個彩色物件,例如您的臉部,然後它會對其進行跟蹤。\n"
"這將從攝像機讀取資料(預設為0,或使用者輸入的攝像機編號)\n"
"用法:\n\t";
cout << argv[0] << " [攝像機編號]\n";
cout << hot_keys;
}
const char* keys =
{
"{help h | | 顯示幫助資訊}{@camera_number| 0 | 攝像機編號}"
};
int main( int argc, const char** argv )
{
Rect trackWindow;
int hsize = 16;
float hranges[] = {0,180};
const float* phranges = hranges;
CommandLineParser parser(argc, argv, keys);\n
if (parser.has("help"))
{
help(argv);
return 0;
}
int camNum = parser.get<int>(0);
cap.open(camNum);
if( !cap.isOpened() )
{
help(argv);
cout << "***無法初始化捕獲...***\n";
cout << "當前引數值:\n";
parser.printMessage();
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 )
{
// 物件已由使用者選擇,一次性設定 CAMShift 搜尋屬性
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; // 除非使用者選擇新的 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<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 );
}
}
// 執行 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;
}
如果陣列沒有元素,則返回 true。
int64_t int64
n 維密集陣列類
定義 mat.hpp:830
MatSize size
定義 mat.hpp:2187
void create(int rows, int cols, int type)
如果需要,分配新的陣列資料。
int depth() const
返回矩陣元素的深度。
_Tp & at(int i0=0)
返回指定陣列元素的引用。
int cols
定義 mat.hpp:2165
int rows
行列數,或當矩陣維度超過2維時為(-1, -1)
定義 mat.hpp:2165
_Tp y
點的 y 座標
定義 types.hpp:202
_Tp x
點的 x 座標
定義 types.hpp:201
2D 矩形的模板類。
定義 types.hpp:444
_Tp area() const
矩形的面積 (寬度*高度)
_Tp x
左上角的 x 座標
定義 types.hpp:487
_Tp y
左上角的 y 座標
定義 types.hpp:488
_Tp width
矩形的寬度
定義 types.hpp:489
_Tp height
矩形的高度
定義 types.hpp:490
該類表示平面上的旋轉(即非正交)矩形。
定義 types.hpp:538
該類定義了迭代演算法的終止條件。
定義 types.hpp:893
短數值向量的模板類,是 Matx 的一個特例。
定義 matx.hpp:369
用於從影片檔案、影像序列或攝像機捕獲影片的類。
Definition videoio.hpp:772
virtual bool open(const String &filename, int apiPreference=CAP_ANY)
開啟影片檔案、捕獲裝置或 IP 影片流進行影片捕獲。
virtual bool isOpened() const
如果影片捕獲已初始化,則返回 true。
void bitwise_not(InputArray src, OutputArray dst, InputArray mask=noArray())
反轉陣列的每個位。
void inRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst)
檢查陣列元素是否介於另外兩個陣列的元素之間。
void mixChannels(const Mat *src, size_t nsrcs, Mat *dst, size_t ndsts, const int *fromTo, size_t npairs)
將指定通道從輸入陣列複製到輸出陣列的指定通道。
void normalize(InputArray src, InputOutputArray dst, double alpha=1, double beta=0, int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray())
對陣列的範數或值範圍進行歸一化。
CV_8UC3
#define CV_8UC3
#define MIN(a, b)
定義 cvdef.h:514
#define MAX(a, b)
定義 cvdef.h:518
GMat mask(const GMat &src, const GMat &mask)
將掩碼應用於矩陣。
void imshow(const String &winname, InputArray mat)
在指定視窗中顯示影像。
int waitKey(int delay=0)
等待按鍵按下。
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
建立視窗。
void destroyWindow(const String &winname)
銷燬指定視窗。
void setMouseCallback(const String &winname, MouseCallback onMouse, void *userdata=0)
為指定視窗設定滑鼠處理程式。
int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
建立滑動條並將其附加到指定視窗。
void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0, AlgorithmHint hint=cv::ALGO_HINT_DEFAULT)
將影像從一個顏色空間轉換為另一個顏色空間。
void rectangle(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
繪製一個簡單、粗或填充的矩形。
void ellipse(InputOutputArray img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
繪製簡單或粗橢圓弧或填充橢圓扇區。
void calcBackProject(const Mat *images, int nimages, const int *channels, InputArray hist, OutputArray backProject, const float **ranges, double scale=1, bool uniform=true)
計算直方圖的反向投影。
void calcHist(const Mat *images, int nimages, const int *channels, InputArray mask, OutputArray hist, int dims, const int *histSize, const float **ranges, bool uniform=true, bool accumulate=false)
計算一組陣列的直方圖。
RotatedRect CamShift(InputArray probImage, Rect &window, TermCriteria criteria)
Finds an object center, size, and orientation.
int main(int argc, char *argv[])
定義 highgui_qt.cpp:3
定義 core.hpp:107
STL 名稱空間。