這篇文章是Andrew Davison博士發布的有關自然用戶界面(NUI)系列的一部分,內容涉及使用JavaCV從網絡攝像頭視頻提要中檢測手。
注意:可以從http://fivedots.coe.psu.ac.th/~ad/jg/nui055/下載本章的所有源代碼。
第5章的彩色斑點檢測代碼(可從http://fivedots.coe.psu.ac.th/~ad/jg/nui05/獲得 )可以用作其他形狀分析器的基礎,我將在此處進行說明。通過擴展它來檢測手和手指。 在圖1中,我的左手戴著黑手套。 我的Handy應用程序嘗試查找并標記拇指,食指,中指,無名指和小指。 在指尖和手的重心(COG)之間繪制黃線。
圖1.檢測左手和手指。
我使用了第5章的HSVSelector應用程序來確定黑手套的合適HSV范圍。 在執行圖2所示的步驟之前,Handy會加載這些范圍,以獲取手部的輪廓,其COG和相對于水平面的方向。
圖2。找到手輪廓。
圖2中的各個階段幾乎與第5章第4.1節中的ColorRectDetector.findRect()方法執行的階段相同。但是,Handy繼續進行處理,使用凸包和凸凹缺陷來定位并標記手中的指尖輪廓。 這些附加步驟如圖3所示。
圖3.查找和標記指尖。
船體和缺陷是通過標準的OpenCV操作從輪廓獲得的,我將在下面進行解釋。 但是,命名手指的最后一步使用了一種頗為怪異的策略,該策略假定輪廓的缺陷是針對伸出的左手。 拇指和食指基于它們相對于COG的角度位置來定位,而其他手指則根據它們相對于那些手指的位置來標識。 這個過程非常脆弱,并且很容易混淆,如圖4所示。
圖4.錯誤的中指。
但是,該技術相當可靠,通常至少可以識別拇指和食指,而與手的方向無關,這對于基本的手勢處理來說應該足夠了。 但是,該應用程序無法識別手勢,希望它將成為下一章的主題。
Handy的類圖如圖5所示,僅列出了公共方法。
圖5.方便的類圖。
Handy的頂級與第5章中的BlobsDrumming應用程序的頂級并行(例如,參見第5章的圖11??),其中Handy類管理JFrame和HandPanel,顯示帶注釋的網絡攝像頭圖像。 圖2和3總結的圖像分析由HandDetector類執行,該類通過調用update()傳遞給當前的網絡攝像頭快照。 當HandPanel調用HandDetector.draw()時,它將繪制當前標記的指尖,COG和連接線。
1.分析網絡攝像頭圖像
update()方法實質上是實現圖2和圖3的一系列調用。
// globals
private static final int IMG_SCALE = 2; // scaling applied to webcam image// HSV ranges defining the glove color
private int hueLower, hueUpper, satLower, satUpper,briLower, briUpper;// OpenCV elements
private IplImage hsvImg; // HSV version of webcam image
private IplImage imgThreshed; // threshold for HSV settings// hand details
private Point cogPt; // center of gravity (COG) of contour
private int contourAxisAngle; // contour's main axis angle relative to the horiz (in degrees)
private ArrayList fingerTips;public void update(BufferedImage im)
{BufferedImage scaleIm = scaleImage(im, IMG_SCALE); // reduce the size of the image to make processing faster// convert image format to HSVcvCvtColor(IplImage.createFrom(scaleIm), hsvImg, CV_BGR2HSV);// threshold image using loaded HSV settings for user's glovecvInRangeS(hsvImg, cvScalar(hueLower, satLower, briLower, 0),cvScalar(hueUpper, satUpper, briUpper, 0),imgThreshed);cvMorphologyEx(imgThreshed, imgThreshed, null, null,CV_MOP_OPEN, 1);// erosion followed by dilation on the image to remove// specks of white while retaining the image sizeCvSeq bigContour = findBiggestContour(imgThreshed);if (bigContour == null)return;extractContourInfo(bigContour, IMG_SCALE);// find the COG and angle to horizontal of the contourfindFingerTips(bigContour, IMG_SCALE);// detect the fingertips positions in the contournameFingers(cogPt, contourAxisAngle, fingerTips);
} // end of update()
update()首先縮放提供的網絡攝像頭圖像以提高處理速度。 然后,它將圖片轉換為HSV格式,以便可以使用黑手套的HSV范圍生成閾值圖像。 這對應于圖2的第一行,盡管實際上將閾值渲染為黑色背景上的白色像素。
減去小斑點的閾值傳遞給findBiggestContour(); 在隨后的處理階段中,假定所得輪廓是用戶的手。 extractContourInfo()分析輪廓以找到手的重心(COG)及其相對于水平面的方向,這些重心存儲在cogPt和ContourAxisAngle全局變量中。 extractContourInfo()的完成對應于圖2的末尾。
findFingerTips()方法將凸包包裹在輪廓周圍,以識別形狀的缺陷(圖3的頂行),我們假設這是手的手指。 經過少量過濾以減少缺陷數量之后,其余缺陷將被視為指尖坐標,并存儲在全局fingerTips列表中。
nameFingers()標記手指(假設拇指和食指在手的左側),完成圖3的階段。
1.1找到最大的輪廓
findBiggestContour()使用OpenCV函數cvFindContours()創建輪廓列表。 對于我的二進制閾值圖像,輪廓是白色像素的區域(或斑點)。 每個斑點由一個邊界框近似,并且選擇并返回與最大框相對應的輪廓。
// globals
private static final float SMALLEST_AREA = 600.0f;// ignore smaller contour areasprivate CvMemStorage contourStorage;private CvSeq findBiggestContour(IplImage imgThreshed)
{CvSeq bigContour = null;// generate all the contours in the threshold image as a listCvSeq contours = new CvSeq(null);cvFindContours(imgThreshed, contourStorage, contours,Loader.sizeof(CvContour.class),CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);// find the largest contour in the list based on bounded box sizefloat maxArea = SMALLEST_AREA;CvBox2D maxBox = null;while (contours != null && !contours.isNull()) {if (contours.elem_size() > 0) {CvBox2D box = cvMinAreaRect2(contours, contourStorage);if (box != null) {CvSize2D32f size = box.size();float area = size.width() * size.height();if (area > maxArea) {maxArea = area;bigContour = contours;}}}contours = contours.h_next();}return bigContour;
} // end of findBiggestContour()
cvFindContours()可以返回以不同類型的數據結構收集在一起的不同類型的輪廓。 我生成最簡單的輪廓,將它們存儲在線性列表中,可以使用while循環進行搜索。
經過一些試驗,我在600平方像素的有邊界框上放置了一個下限,以濾除圍繞圖像噪點的小框。 這意味著,如果findBiggestContour()找不到足夠大的框,則可能返回null。
1.2計算COG和水平角
圖2所示的下一步是通過調用extractContourInfo()查找COG和與手部輪廓水平線的夾角。 在此,HandDetector中的代碼從ColorRectDetector.findRect()在第5章中進行的分析開始成為公司的一部分。在該章的4.2節中,利用輪廓周圍的包圍盒獲取中心和方向。 這是足夠的,因為基礎形狀是矩形卡片,因此輪廓和框幾乎相同。 但是,手周圍的邊界框可能很容易產生與手本身完全不同的COG或角度。 在這種情況下,有必要利用力矩直接分析手部輪廓而不是邊界框。
我在第3章中使用了空間矩來查找二進制圖像的COG。 可以將相同的技術應用于輪廓以找到其中心(或質心)。 我還可以計算二階混合矩,它提供了有關質心周圍像素散布的信息。 可以組合二階矩以返回輪廓的主軸相對于x軸的方向(或角度)。
回顧第三章的OpenCV矩符號,m()矩函數定義為:
該函數帶有兩個參數p和q,它們用作x和y的冪。 I()函數是由像素的(x,y)坐標定義的像素的強度。 n是組成形狀的像素數。
如果考慮圖6中的輪廓,則θ是其主軸線與水平面的角度,+ y軸指向下方。
圖6.輪廓線及其主軸線。
就m()函數而言,可以證明:
如下所示的extractContourInfo()方法使用空間矩獲取輪廓的質心,并使用cvGetCentralMoment()根據上述公式計算主軸角; 這些結果存儲在全局變量cogPt和ContourAxisAngle中,以備后用。
// globals
private Point cogPt; // center of gravity (COG) of contour
private int contourAxisAngle; // contour's main axis angle relative to horizontal (in degrees)private ArrayList fingerTips;private void extractContourInfo(CvSeq bigContour, int scale)
{CvMoments moments = new CvMoments();cvMoments(bigContour, moments, 1);// center of gravitydouble m00 = cvGetSpatialMoment(moments, 0, 0) ;double m10 = cvGetSpatialMoment(moments, 1, 0) ;double m01 = cvGetSpatialMoment(moments, 0, 1);if (m00 != 0) { // calculate centerint xCenter = (int) Math.round(m10/m00)*scale;int yCenter = (int) Math.round(m01/m00)*scale;cogPt.setLocation(xCenter, yCenter);}double m11 = cvGetCentralMoment(moments, 1, 1);double m20 = cvGetCentralMoment(moments, 2, 0);double m02 = cvGetCentralMoment(moments, 0, 2);contourAxisAngle = calculateTilt(m11, m20, m02);// deal with hand contour pointing downwards/* uses fingertips information generated on the last update ofthe hand, so will be out-of-date */if (fingerTips.size() > 0) {int yTotal = 0;for(Point pt : fingerTips)yTotal += pt.y;int avgYFinger = yTotal/fingerTips.size();if (avgYFinger > cogPt.y) // fingers below COGcontourAxisAngle += 180;}contourAxisAngle = 180 - contourAxisAngle; /* this makes the angle relative to a positive y-axis thatruns up the screen */
} // end of extractContourInfo()private int calculateTilt(double m11, double m20, double m02)
{double diff = m20 - m02;if (diff == 0) {if (m11 == 0)return 0;else if (m11 > 0)return 45;else // m11 < 0return -45;}double theta = 0.5 * Math.atan2(2*m11, diff);int tilt = (int) Math.round( Math.toDegrees(theta));if ((diff > 0) && (m11 == 0))return 0;else if ((diff < 0) && (m11 == 0))return -90;else if ((diff > 0) && (m11 > 0)) // 0 to 45 degreesreturn tilt;else if ((diff > 0) && (m11 < 0)) // -45 to 0return (180 + tilt); // change to counter-clockwise angleelse if ((diff < 0) && (m11 > 0)) // 45 to 90return tilt;else if ((diff < 0) && (m11 < 0)) // -90 to -45return (180 + tilt); // change to counter-clockwise angleSystem.out.println("Error in moments for tilt angle");return 0;
} // end of calculateTilt()
Johannes Kilian在http://public.cranfield.ac.uk/c5354/teaching/dip/opencv/SimpleImageAnalysisbyMoments.pdf的Johannes Kilian撰寫的“按時進行的簡單圖像分析”中對OpenCV中的時刻進行了深入的說明。 calculateTilt()內的代碼基于Kilian論文表1中列出的θ特殊情況。
不幸的是,軸角無法區分手指指向上方的手和手指指向下方的手,因此有必要檢查指尖相對于COG的相對位置,以決定是否應調整角度。 問題在于,只有在檢查了手部輪廓的凸包是否存在缺陷(在extractContourInfo()完成之后才發生)之后,該信息才可用。
我的解決方案是使用在上一次調用update()時計算出的指尖坐標,該指針分析了當前幀之前的攝像頭幀。 數據將是過時的,但是在兩次捕捉之間的200毫秒間隔內指針不會移動太多。
1.3找到指尖
指尖的識別在圖3的第一行中進行; 在代碼中,通過OpenCV的cvConvexHull2()將凸包包裹在輪廓上,然后通過cvConvexityDefects()將多邊形與輪廓進行比較以查找其缺陷。
通過使用輪廓的低多邊形近似而不是原始的近似來加快船體創建和缺陷分析的速度。
這些階段在findFingerTips()方法的前半部分執行:
// globals
private static final int MAX_POINTS = 20; // max number of points stored in an array// OpenCV elements
private CvMemStorage contourStorage, approxStorage,hullStorage, defectsStorage;// defects data for the hand contour
private Point[] tipPts, foldPts;
private float[] depths;private void findFingerTips(CvSeq bigContour, int scale)
{CvSeq approxContour = cvApproxPoly(bigContour,Loader.sizeof(CvContour.class),approxStorage, CV_POLY_APPROX_DP, 3, 1);// reduce number of points in the contourCvSeq hullSeq = cvConvexHull2(approxContour,hullStorage, CV_COUNTER_CLOCKWISE, 0);// find the convex hull around the contourCvSeq defects = cvConvexityDefects(approxContour,hullSeq, defectsStorage);// find the defect differences between the contour and hullint defectsTotal = defects.total();if (defectsTotal > MAX_POINTS) {System.out.println("Processing " + MAX_POINTS + " defect pts");defectsTotal = MAX_POINTS;}// copy defect information from defects sequence into arraysfor (int i = 0; i < defectsTotal; i++) {Pointer pntr = cvGetSeqElem(defects, i);CvConvexityDefect cdf = new CvConvexityDefect(pntr);CvPoint startPt = cdf.start();tipPts[i] = new Point( (int)Math.round(startPt.x()*scale),(int)Math.round(startPt.y()*scale));// array contains coords of the fingertipsCvPoint endPt = cdf.end();CvPoint depthPt = cdf.depth_point();foldPts[i] = new Point( (int)Math.round(depthPt.x()*scale),(int)Math.round(depthPt.y()*scale));//array contains coords of the skin fold between fingersdepths[i] = cdf.depth()*scale;// array contains distances from tips to folds}reduceTips(defectsTotal, tipPts, foldPts, depths);
} // end of findFingerTips()
findFingerTips()的后半部分從缺陷序列中提取尖端和褶皺坐標以及深度。 之前使用CV_COUNTER_CLOCKWISE參數調用凸包方法cvConvexHull2()意味著將以逆時針順序存儲坐標,如圖7所示。
圖7.指尖,褶皺和深度。
指尖存儲在tipPts []數組中,手指在foldPts []中折疊(手指之間的凹痕),深度在depths []中。
如圖7所示,分析通常會產生太多缺陷,因此在findFingerTips()的末尾會調用reduceTips()。 它應用了兩個簡單的測試來濾除不太可能是指尖的缺陷-丟棄缺陷深度較淺的點,并在其相鄰折疊點之間以太大的角度進行坐標。 兩者的示例如圖8所示。
圖8.淺深度和廣角。
reduceTips()將其余的提示點存儲在全局fingerTips列表中:
// globals
private static final int MIN_FINGER_DEPTH = 20;
private static final int MAX_FINGER_ANGLE = 60; // degreesprivate ArrayList fingerTips;private void reduceTips(int numPoints, Point[] tipPts,Point[] foldPts, float[] depths)
{fingerTips.clear();for (int i=0; i < numPoints; i++) {if (depths[i] < MIN_FINGER_DEPTH) // defect too shallowcontinue;// look at fold points on either side of a tipint pdx = (i == 0) ? (numPoints-1) : (i - 1); // predecessor of iint sdx = (i == numPoints-1) ? 0 : (i + 1); // successor of iint angle = angleBetween(tipPts[i], foldPts[pdx], foldPts[sdx]);if (angle >= MAX_FINGER_ANGLE) continue; // angle between finger and folds too wide// this point is probably a fingertip, so add to listfingerTips.add(tipPts[i]);}
} // end of reduceTips()private int angleBetween(Point tip, Point next, Point prev)
// calculate the angle between the tip and its neighboring folds
// (in integer degrees)
{return Math.abs( (int)Math.round(Math.toDegrees(Math.atan2(next.x - tip.x, next.y - tip.y) -Math.atan2(prev.x - tip.x, prev.y - tip.y)) ));
}
1.4命名手指
nameFingers()使用指尖坐標列表以及輪廓的COG和軸角度來分兩步標記手指。 首先,它會基于它們相對于COG的可能角度調用labelThumbIndex()來標記拇指和食指,假設它們位于手的左側。 nameFingers()嘗試根據相對于拇指和食指的已知順序在labelUnknowns()中標記其他手指。
// globals
private ArrayList namedFingers;private void nameFingers(Point cogPt, int contourAxisAngle,ArrayList fingerTips)
{ // reset all named fingers to unknownnamedFingers.clear();for (int i=0; i < fingerTips.size(); i++)namedFingers.add(FingerName.UNKNOWN);labelThumbIndex(fingerTips, namedFingers);labelUnknowns(namedFingers);
} // end of nameFingers()
Finger ID及其相對順序在FingerName枚舉中維護:
public enum FingerName {LITTLE, RING, MIDDLE, INDEX, THUMB, UNKNOWN;public FingerName getNext(){ int nextIdx = ordinal()+1;if (nextIdx == (values().length))nextIdx = 0;return values()[nextIdx]; } // end of getNext()public FingerName getPrev(){ int prevIdx = ordinal()-1;if (prevIdx < 0)prevIdx = values().length-1;return values()[prevIdx]; } // end of getPrev()} // end of FingerName enum
可能的手指名稱之一是UNKNOWN,該名稱用于在調用命名方法之前標記所有指尖。
labelThumbIndex()嘗試根據圖9中所示的角度范圍來標記拇指和食指。
圖9.拇指和食指的角度范圍。
食指可以圍繞COG旋轉60至120度,而拇指可以在120至200度之間移動。 我通過反復試驗得出了這些角度,他們認為手是筆直向上的。
labelThumbIndex()還假設拇指和食指最有可能存儲在fingerTips列表的末尾,因為輪廓船體是按逆時針順序構建的。 因此,通過向后遍歷列表,可以增加與正確缺陷匹配的機會。
// globals
private static final int MIN_THUMB = 120; // angle ranges
private static final int MAX_THUMB = 200;private static final int MIN_INDEX = 60;
private static final int MAX_INDEX = 120;// hand details
private Point cogPt
private int contourAxisAngle; private void labelThumbIndex(ArrayList fingerTips,ArrayList nms)
{boolean foundThumb = false;boolean foundIndex = false;int i = fingerTips.size()-1;while ((i >= 0)) {int angle = angleToCOG(fingerTips.get(i),cogPt, contourAxisAngle);// check for thumbif ((angle <= MAX_THUMB) && (angle>MIN_THUMB) && !foundThumb) {nms.set(i, FingerName.THUMB);foundThumb = true;}// check for indexif ((angle <= MAX_INDEX) && (angle > MIN_INDEX) && !foundIndex) {nms.set(i, FingerName.INDEX);foundIndex = true;}i--;}
} // end of labelThumbIndex()
angleToCOG()計算指尖相對于COG的角度,記住要記住輪廓軸角度,以便使手筆直向上。
private int angleToCOG(Point tipPt, Point cogPt,int contourAxisAngle)
{int yOffset = cogPt.y - tipPt.y; // make y positive up screenint xOffset = tipPt.x - cogPt.x;double theta = Math.atan2(yOffset, xOffset);int angleTip = (int) Math.round( Math.toDegrees(theta));return angleTip + (90 - contourAxisAngle);// this ensures that the hand is orientated straight up
} // end of angleToCOG()
labelUnknowns()傳遞了一個手指名稱列表,該列表希望在某些位置包含THUMB和INDEX,而在其他位置包含UNKNOWN。 使用命名的手指作為起點,根據手指在FingerName枚舉中的順序,將UNKNOWN更改為手指名稱。
private void labelUnknowns(ArrayList nms)
{// find first named fingerint i = 0;while ((i < nms.size()) && (nms.get(i) == FingerName.UNKNOWN))i++;if (i == nms.size()) // no named fingers found, so give upreturn;FingerName name = nms.get(i);labelPrev(nms, i, name); // fill-in backwardslabelFwd(nms, i, name); // fill-in forwards
} // end of labelUnknowns()
labelPrev()和labelFwd()的區別僅在于它們在名稱列表中移動的方向。 labelPrev()向后移動以嘗試將UNKNOWNS更改為已命名的手指,但前提是尚未將名稱分配給列表。
2.畫出手指
由update()執行的分析將產生指尖點列表(在全局fingerTips中),關聯的已命名手指的列表(在namedFingers中)以及輪廓COG和軸角度。 除角度外,所有這些都由draw()用來將命名的手指標簽添加到網絡攝像頭圖像中,如下圖1和圖10所示。
圖10.命名的手指和未知的手指。
一個未知的手指“尖端”(在namedFingers中標記為UNKNOWN)被繪制為紅色圓圈。
// globals
private Point cogPt;
private ArrayList fingerTips;
private ArrayList namedFingers;public void draw(Graphics2D g2d)
{if (fingerTips.size() == 0)return;g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); // line smoothingg2d.setPaint(Color.YELLOW);g2d.setStroke(new BasicStroke(4)); // thick yellow pen// label tips in red or green, and draw lines to named tipsg2d.setFont(msgFont);for (int i=0; i < fingerTips.size(); i++) {Point pt = fingerTips.get(i);if (namedFingers.get(i) == FingerName.UNKNOWN) {g2d.setPaint(Color.RED); // unnamed fingertip is redg2d.drawOval(pt.x-8, pt.y-8, 16, 16);g2d.drawString("" + i, pt.x, pt.y-10); // label with a digit}else { // draw yellow line to the named fingertip from COGg2d.setPaint(Color.YELLOW);g2d.drawLine(cogPt.x, cogPt.y, pt.x, pt.y);g2d.setPaint(Color.GREEN); // named fingertip is greeng2d.drawOval(pt.x-8, pt.y-8, 16, 16);g2d.drawString(namedFingers.get(i).toString().toLowerCase(),pt.x, pt.y-10);}}// draw COGg2d.setPaint(Color.GREEN);g2d.fillOval(cogPt.x-8, cogPt.y-8, 16, 16);
} // end of draw()
3.手勢檢測
Handy應用程序會盡力將已命名的指尖轉換為手勢,這需要分析手指隨著時間在空間中的移動方式。
初步測試表明,Handy僅在涉及伸出的拇指和/或食指(也許與其他手指結合在一起)時,才能可靠地識別手勢。 這種手勢包括圖11所示的“勝利”,“波浪”,“良好”,“指向”和“槍支”。
圖11.適用于便捷式檢測的手勢。
Handy無法檢測到的常見手勢是“ ok”(參見圖12),因為它需要將手指放在一起,而這不能僅根據輪廓缺陷來檢測到。
圖12.不合適的“確定”手勢。
參考: Java Advent Calendar博客上的JCG合作伙伴 Attila-Mihaly Balazs 使用JavaCV進行的手和手指檢測 。
翻譯自: https://www.javacodegeeks.com/2012/12/hand-and-finger-detection-using-javacv.html