C++ OpenCV最后一个凸面缺陷不正确
我正在尝试编写代码来跟踪手。我使用凸面缺陷函数来寻找手指,但出于某种原因,最后一个缺陷似乎总是有问题 对不起,我是新加入论坛的,所以不能发布图片 青色线是轮廓线,黄色线是外壳点,红色线是缺陷点。如您所见,最后一个缺陷点从轮廓的错误一侧检测缺陷 这是我的密码:C++ OpenCV最后一个凸面缺陷不正确,c++,opencv,convexity-defects,C++,Opencv,Convexity Defects,我正在尝试编写代码来跟踪手。我使用凸面缺陷函数来寻找手指,但出于某种原因,最后一个缺陷似乎总是有问题 对不起,我是新加入论坛的,所以不能发布图片 青色线是轮廓线,黄色线是外壳点,红色线是缺陷点。如您所见,最后一个缺陷点从轮廓的错误一侧检测缺陷 这是我的密码: #include "opencv2\opencv.hpp" using namespace cv; using namespace std; int main() { VideoCapture cap(0); Mat s
#include "opencv2\opencv.hpp"
using namespace cv;
using namespace std;
int main() {
VideoCapture cap(0);
Mat src, gray, background, binary, diff;
cap >> background;
cvtColor(background, background, CV_BGR2GRAY);
vector<vector<Point>> contours;
vector < vector<int>> hullI = vector<vector<int>>(1);
vector < vector<Point>> hullP = vector<vector<Point>>(1);
vector<Vec4i> defects;
while (waitKey(30)!='q') {
cap >> src;
cvtColor(src, gray, CV_BGR2GRAY);
blur(gray, gray, Size(3, 3));
absdiff(gray, background, diff);
threshold(diff, binary, 15, 255, THRESH_BINARY);
erode(binary, binary, Mat(Size(5, 5), CV_8U));
imshow("binary", binary);
findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
if (!contours.empty()) {
sort(contours.begin(), contours.end(), [](vector<Point> a, vector<Point> b) { return a.size() > b.size(); });
drawContours(src, contours, 0, Scalar(255, 255, 0));
convexHull(contours[0], hullI[0]);
convexHull(contours[0], hullP[0]);
drawContours(src, hullP, 0, Scalar(0, 255, 255));
if (hullI[0].size() > 2) {
convexityDefects(contours[0], hullI[0], defects);
for (Vec4i defect : defects) {
line(src, contours[0][defect[0]], contours[0][defect[2]], Scalar(0, 0, 255));
line(src, contours[0][defect[1]], contours[0][defect[2]], Scalar(0, 0, 255));
}
}
}
imshow("src", src);
char key = waitKey(30);
if (key == 'q')break;
else if (key == 'p') waitKey();
else if (key == 'b') {
cap >> background;
cvtColor(background, background, CV_BGR2GRAY);
}
}
}
我已经通过实验证实,缺陷向量中的最后一个缺陷也会发生这种情况。这是opencv中的一个bug还是我做错了什么?我对您的代码进行了一些小的修改,下面的图像显示opencv版本是3.2 正如您在结果图像上看到的,它按预期工作。可能您正在使用一个旧版本的OpenCV,并且得到了一个错误的结果。我想这是最近修复的一个bug
我有一个解决方案,其中包括使用OpenCV检测皮肤。我用Python实现它,你可以轻松地转换成C++。 我使用以下方法获得了您上传的图像的HSV值:
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
这是人体皮肤HSV值的范围:
l = np.array([0, 48, 80], dtype = "uint8")
u = np.array([20, 255, 255], dtype = "uint8")
skin_img = cv2.inRange(hsv_img, l, u)
cv2.imshow("Hand", skin_img)
然后,我进行了形态学扩张并获得以下结果:
您现在可以应用等高线外壳并查找凸面缺陷。hi@Matthew Drill感谢您接受我的回答。您是否使用了较旧版本的OpenCV?
l = np.array([0, 48, 80], dtype = "uint8")
u = np.array([20, 255, 255], dtype = "uint8")
skin_img = cv2.inRange(hsv_img, l, u)
cv2.imshow("Hand", skin_img)