目录
  • 1 简介
  • 2 传统机器视觉的手势检测
    • 2.1 轮廓检测法
    • 2.2 算法结果
    • 2.3 整体代码实现
  • 3 深度学习方法做手势识别
    • 3.1 经典的卷积神经网络
    • 3.2 yolo系列
    • 3.3 ssd
    • 3.4 实现步骤
    • 3.5 关键代码
  • 4 实现手势交互

    1 简介

    今天学长向大家介绍一个机器视觉项目

    基于机器视觉opencv的手势检测 手势识别 算法

    2 传统机器视觉的手势检测

    普通机器视觉手势检测的基本流程如下:

    其中轮廓的提取,多边形拟合曲线的求法,凸包集和凹陷集的求法都是采用opencv中自带的函数。手势数字的识别是利用凸包点以及凹陷点和手部中心点的几何关系,简单的做了下逻辑判别了(可以肯定的是这种方法很烂),具体的做法是先在手部定位出2个中心点坐标,这2个中心点坐标之间的距离阈值由程序设定,其中一个中心点就是利用openni跟踪得到的手部位置。有了这2个中心点的坐标,在程序中就可以分别计算出在这2个中心点坐标上的凸凹点的个数。当然了,这样做的前提是用人在做手势表示数字的同时应该是将手指的方向朝上(因为没有像机器学习那样通过样本来训练,所以使用时条件要苛刻很多)。利用上面求出的4种点的个数(另外程序中还设置了2个辅助计算点的个数,具体见代码部分)和简单的逻辑判断就可以识别出数字0~5了。其它的数字可以依照具体的逻辑去设计(还可以设计出多位数字的识别),只是数字越多设计起来越复杂,因为要考虑到它们之间的干扰性,且这种不通用的设计方法也没有太多的实际意义。

    2.1 轮廓检测法

    使用 void convexitydefects(inputarray contour, inputarray convexhull, outputarray convexitydefects) 方法

    该函数的作用是对输入的轮廓contour,凸包集合来检测其轮廓的凸型缺陷,一个凸型缺陷结构体包括4个元素,缺陷起点坐标,缺陷终点坐标,缺陷中离凸包线距离最远的点的坐标,以及此时最远的距离。参数3即其输出的凸型缺陷结构体向量。

    其凸型缺陷的示意图如下所示:

    第1个参数虽然写的是contour,字面意思是轮廓,但是本人实验过很多次,发现如果该参数为目标通过轮廓检测得到的原始轮廓的话,则程序运行到onvexitydefects()函数时会报内存错误。因此本程序中采用的不是物体原始的轮廓,而是经过多项式曲线拟合后的轮廓,即多项式曲线,这样程序就会顺利地运行得很好。另外由于在手势识别过程中可能某一帧检测出来的轮廓非常小(由于某种原因),以致于少到只有1个点,这时候如果程序运行到onvexitydefects()函数时就会报如下的错误:

    int mat::checkvector(int _elemchannels, int _depth, bool _requirecontinuous) const
    
    {
    
        return (depth() == _depth || _depth <= 0) &&
    
            (iscontinuous() || !_requirecontinuous) &&
    
            ((dims == 2 && (((rows == 1 || cols == 1) && channels() == _elemchannels) || (cols == _elemchannels))) ||
    
            (dims == 3 && channels() == 1 && size.p[2] == _elemchannels && (size.p[0] == 1 || size.p[1] == 1) &&
    
             (iscontinuous() || step.p[1] == step.p[2]*size.p[2])))
    
        ? (int)(total()*channels()/_elemchannels) : -1;
    
    }
    

    该函数源码大概意思就是说对应的mat矩阵如果其深度,连续性,通道数,行列式满足一定条件的话就返回mat元素的个数和其通道数的乘积,否则返回-1;而本文是要求其返回值大于3,有得知此处输入多边形曲线(即参数1)的通道数为2,所以还需要求其元素的个数大于1.5,即大于2才满足ptnum > 3。简单的说就是用convexitydefects()函数来对多边形曲线进行凹陷检测时,必须要求参数1曲线本身至少有2个点(也不知道这样分析对不对)。因此本人在本次程序convexitydefects()函数前加入了if(mat(approx_poly_curve).checkvector(2, cv_32s) > 3)来判断,只有满足该if条件,才会进行后面的凹陷检测。这样程序就不会再出现类似的bug了。

    第2个参数一般是由opencv中的函数convexhull()获得的,一般情况下该参数里面存的是凸包集合中的点在多项式曲线点中的位置索引,且该参数以vector的形式存在,因此参数convexhull中其元素的类型为unsigned int。在本次凹陷点检测函数convexitydefects()里面根据文档,要求该参数为mat型。因此在使用convexitydefects()的参数2时,一般将vector直接转换mat型。

    参数3是一个含有4个元素的结构体的集合,如果在c++的版本中,该参数可以直接用vector来代替,vec4i中的4个元素分别表示凹陷曲线段的起始坐标索引,终点坐标索引,离凸包集曲线最远点的坐标索引以及此时的最远距离值,这4个值都是整数。在c版本的opencv中一般不是保存的索引,而是坐标值。

    2.2 算法结果

    数字“0”的识别结果:

    数字“1”的识别结果

    数字“2”的识别结果

    数字“3”的识别结果:

    数字“4”的识别结果:

    数字“5”的识别结果:

    2.3 整体代码实现

    2.3.1 算法流程

    学长实现过程和上面的系统流程图类似,大概过程如下:

    1. 求出手部的掩膜

    2. 求出掩膜的轮廓

    3. 求出轮廓的多变形拟合曲线

    4. 求出多边形拟合曲线的凸包集,找出凸点

    5. 求出多变形拟合曲线的凹陷集,找出凹点

    6. 利用上面的凸凹点和手部中心点的几何关系来做简单的数字手势识别

    (这里用的是c语言写的,这个代码是学长早期写的,同学们需要的话,学长出一个python版本的)

    #include <iostream>
    #include "opencv2/highgui/highgui.hpp"
    #include "opencv2/imgproc/imgproc.hpp"
    #include <opencv2/core/core.hpp>
    #include "copenni.cpp"
    #include <iostream>
    #define depth_scale_factor 255./4096.
    #define roi_hand_width 140
    #define roi_hand_height 140
    #define median_blur_k 5
    #define xres  640
    #define yres  480
    #define depth_segment_thresh 5
    #define max_hands_color 10
    #define max_hands_number  10
    #define hand_likely_area 2000
    #define delta_point_distence 25     //手部中心点1和中心点2距离的阈值
    #define segment_point1_distance 27  //凸点与手部中心点1远近距离的阈值
    #define segment_point2_distance 30  //凸点与手部中心点2远近距离的阈值
    using namespace cv;
    using namespace xn;
    using namespace std;
    int main (int argc, char **argv)
    {
    unsigned int convex_number_above_point1 = 0;
    unsigned int concave_number_above_point1 = 0;
    unsigned int convex_number_above_point2 = 0;
    unsigned int concave_number_above_point2 = 0;
    unsigned int convex_assist_above_point1 = 0;
    unsigned int convex_assist_above_point2 = 0;
    unsigned int point_y1 = 0;
    unsigned int point_y2 = 0;
    int number_result = -1;
    bool recognition_flag = false;  //开始手部数字识别的标志
    vector<scalar> color_array;//采用默认的10种颜色
    {
    color_array.push_back(scalar(255, 0, 0));
    color_array.push_back(scalar(0, 255, 0));
    color_array.push_back(scalar(0, 0, 255));
    color_array.push_back(scalar(255, 0, 255));
    color_array.push_back(scalar(255, 255, 0));
    color_array.push_back(scalar(0, 255, 255));
    color_array.push_back(scalar(128, 255, 0));
    color_array.push_back(scalar(0, 128, 255));
    color_array.push_back(scalar(255, 0, 128));
    color_array.push_back(scalar(255, 128, 255));
    }
    vector<unsigned int> hand_depth(max_hands_number, 0);
    vector<rect> hands_roi(max_hands_number, rect(xres/2, yres/2, roi_hand_width, roi_hand_height));
    namedwindow("color image", cv_window_autosize);
    namedwindow("depth image", cv_window_autosize);
    namedwindow("hand_segment", cv_window_autosize);    //显示分割出来的手的区域
    namedwindow("handrecognition", cv_window_autosize); //显示0~5数字识别的图像
    copenni openni;
    if(!openni.initial())
    return 1;
    if(!openni.start())
    return 1;
    while(1) {
    if(!openni.updatedata()) {
    return 1;
    }
    /*获取并显示色彩图像*/
    mat color_image_src(openni.image_metadata_.yres(), openni.image_metadata_.xres(),
    cv_8uc3, (char *)openni.image_metadata_.data());
    mat color_image;
    cvtcolor(color_image_src, color_image, cv_rgb2bgr);
    mat hand_segment_mask(color_image.size(), cv_8uc1, scalar::all(0));
    for(auto ituser = openni.hand_points_.cbegin(); ituser != openni.hand_points_.cend(); ++ituser) {
    point_y1 = ituser->second.y;
    point_y2 = ituser->second.y + delta_point_distence;
    circle(color_image, point(ituser->second.x, ituser->second.y),
    5, color_array.at(ituser->first % color_array.size()), 3, 8);
    /*设置不同手部的深度*/
    hand_depth.at(ituser->first % max_hands_color) = (unsigned int)(ituser->second.z* depth_scale_factor);//ituser->first会导致程序出现bug
    /*设置不同手部的不同感兴趣区域*/
    hands_roi.at(ituser->first % max_hands_number) = rect(ituser->second.x - roi_hand_width/2, ituser->second.y - roi_hand_height/2,
    roi_hand_width, roi_hand_height);
    hands_roi.at(ituser->first % max_hands_number).x =  ituser->second.x - roi_hand_width/2;
    hands_roi.at(ituser->first % max_hands_number).y =  ituser->second.y - roi_hand_height/2;
    hands_roi.at(ituser->first % max_hands_number).width = roi_hand_width;
    hands_roi.at(ituser->first % max_hands_number).height = roi_hand_height;
    if(hands_roi.at(ituser->first % max_hands_number).x <= 0)
    hands_roi.at(ituser->first % max_hands_number).x  = 0;
    if(hands_roi.at(ituser->first % max_hands_number).x > xres)
    hands_roi.at(ituser->first % max_hands_number).x =  xres;
    if(hands_roi.at(ituser->first % max_hands_number).y <= 0)
    hands_roi.at(ituser->first % max_hands_number).y = 0;
    if(hands_roi.at(ituser->first % max_hands_number).y > yres)
    hands_roi.at(ituser->first % max_hands_number).y =  yres;
    }
    imshow("color image", color_image);
    /*获取并显示深度图像*/
    mat depth_image_src(openni.depth_metadata_.yres(), openni.depth_metadata_.xres(),
    cv_16uc1, (char *)openni.depth_metadata_.data());//因为kinect获取到的深度图像实际上是无符号的16位数据
    mat depth_image;
    depth_image_src.convertto(depth_image, cv_8u, depth_scale_factor);
    imshow("depth image", depth_image);
    //取出手的mask部分
    //不管原图像时多少通道的,mask矩阵声明为单通道就ok
    for(auto ituser = openni.hand_points_.cbegin(); ituser != openni.hand_points_.cend(); ++ituser) {
    for(int i = hands_roi.at(ituser->first % max_hands_number).x; i < std::min(hands_roi.at(ituser->first % max_hands_number).x+hands_roi.at(ituser->first % max_hands_number).width, xres); i++)
    for(int j = hands_roi.at(ituser->first % max_hands_number).y; j < std::min(hands_roi.at(ituser->first % max_hands_number).y+hands_roi.at(ituser->first % max_hands_number).height, yres); j++) {
    hand_segment_mask.at<unsigned char>(j, i) = ((hand_depth.at(ituser->first % max_hands_number)-depth_segment_thresh) < depth_image.at<unsigned char>(j, i))
    & ((hand_depth.at(ituser->first % max_hands_number)+depth_segment_thresh) > depth_image.at<unsigned char>(j,i));
    }
    }
    medianblur(hand_segment_mask, hand_segment_mask, median_blur_k);
    mat hand_segment(color_image.size(), cv_8uc3);
    color_image.copyto(hand_segment, hand_segment_mask);
    /*对mask图像进行轮廓提取,并在手势识别图像中画出来*/
    std::vector< std::vector<point> > contours;
    findcontours(hand_segment_mask, contours, cv_retr_list, cv_chain_approx_simple);//找出mask图像的轮廓
    mat hand_recognition_image = mat::zeros(color_image.rows, color_image.cols, cv_8uc3);
    for(int i = 0; i < contours.size(); i++) {  //只有在检测到轮廓时才会去求它的多边形,凸包集,凹陷集
    recognition_flag = true;
    /*找出轮廓图像多边形拟合曲线*/
    mat contour_mat = mat(contours[i]);
    if(contourarea(contour_mat) > hand_likely_area) {   //比较有可能像手的区域
    std::vector<point> approx_poly_curve;
    approxpolydp(contour_mat, approx_poly_curve, 10, true);//找出轮廓的多边形拟合曲线
    std::vector< std::vector<point> > approx_poly_curve_debug;
    approx_poly_curve_debug.push_back(approx_poly_curve);
    drawcontours(hand_recognition_image, contours, i, scalar(255, 0, 0), 1, 8); //画出轮廓
    //            drawcontours(hand_recognition_image, approx_poly_curve_debug, 0, scalar(256, 128, 128), 1, 8); //画出多边形拟合曲线
    /*对求出的多边形拟合曲线求出其凸包集*/
    vector<int> hull;
    convexhull(mat(approx_poly_curve), hull, true);
    for(int i = 0; i < hull.size(); i++) {
    circle(hand_recognition_image, approx_poly_curve[hull[i]], 2, scalar(0, 255, 0), 2, 8);
    /*统计在中心点1以上凸点的个数*/
    if(approx_poly_curve[hull[i]].y <= point_y1) {
    /*统计凸点与中心点1的y轴距离*/
    long dis_point1 = abs(long(point_y1 - approx_poly_curve[hull[i]].y));
    int dis1 = point_y1 - approx_poly_curve[hull[i]].y;
    if(dis_point1 > segment_point1_distance && dis1 >= 0)  {
    convex_assist_above_point1++;
    }
    convex_number_above_point1++;
    }
    /*统计在中心点2以上凸点的个数*/
    if(approx_poly_curve[hull[i]].y <= point_y2)    {
    /*统计凸点与中心点1的y轴距离*/
    long dis_point2 = abs(long(point_y2 - approx_poly_curve[hull[i]].y));
    int dis2 = point_y2 - approx_poly_curve[hull[i]].y;
    if(dis_point2 > segment_point2_distance && dis2 >= 0)  {
    convex_assist_above_point2++;
    }
    convex_number_above_point2++;
    }
    }
    //            /*对求出的多边形拟合曲线求出凹陷集*/
    std::vector<vec4i> convexity_defects;
    if(mat(approx_poly_curve).checkvector(2, cv_32s) > 3)
    convexitydefects(approx_poly_curve, mat(hull), convexity_defects);
    for(int i = 0; i < convexity_defects.size(); i++) {
    circle(hand_recognition_image, approx_poly_curve[convexity_defects[i][2]] , 2, scalar(0, 0, 255), 2, 8);
    /*统计在中心点1以上凹陷点的个数*/
    if(approx_poly_curve[convexity_defects[i][2]].y <= point_y1)
    concave_number_above_point1++;
    /*统计在中心点2以上凹陷点的个数*/
    if(approx_poly_curve[convexity_defects[i][2]].y <= point_y2)
    concave_number_above_point2++;
    }
    }
    }
    /**画出手势的中心点**/
    for(auto ituser = openni.hand_points_.cbegin(); ituser != openni.hand_points_.cend(); ++ituser) {
    circle(hand_recognition_image, point(ituser->second.x, ituser->second.y), 3, scalar(0, 255, 255), 3, 8);
    circle(hand_recognition_image, point(ituser->second.x, ituser->second.y + 25), 3, scalar(255, 0, 255), 3, 8);
    }
    /*手势数字0~5的识别*/
    //"0"的识别
    if((convex_assist_above_point1 ==0 && convex_number_above_point2 >= 2 && convex_number_above_point2 <= 3 &&
    concave_number_above_point2 <= 1 && concave_number_above_point1 <= 1) || (concave_number_above_point1 ==0
    || concave_number_above_point2 == 0) && recognition_flag == true)
    number_result = 0;
    //"1"的识别
    if(convex_assist_above_point1 ==1 && convex_number_above_point1 >=1  && convex_number_above_point1 <=2 &&
    convex_number_above_point2 >=2 && convex_assist_above_point2 == 1)
    number_result = 1;
    //"2"的识别
    if(convex_number_above_point1 == 2 && concave_number_above_point1 == 1 && convex_assist_above_point2 == 2
    /*convex_assist_above_point1 <=1*/ && concave_number_above_point2 == 1)
    number_result = 2;
    //"3"的识别
    if(convex_number_above_point1 == 3 && concave_number_above_point1 <= 3 &&
    concave_number_above_point1 >=1 && convex_number_above_point2 >= 3 && convex_number_above_point2 <= 4 &&
    convex_assist_above_point2 == 3)
    number_result = 3;
    //"4"的识别
    if(convex_number_above_point1 == 4 && concave_number_above_point1 <=3 && concave_number_above_point1 >=2 &&
    convex_number_above_point2 == 4)
    number_result = 4;
    //"5"的识别
    if(convex_number_above_point1 >=4 && convex_number_above_point2 == 5 && concave_number_above_point2 >= 3 &&
    convex_number_above_point2 >= 4)
    number_result = 5;
    if(number_result !=0 && number_result != 1  && number_result != 2 && number_result != 3 && number_result != 4 && number_result != 5)
    number_result == -1;
    /*在手势识别图上显示匹配的数字*/
    std::stringstream number_str;
    number_str << number_result;
    puttext(hand_recognition_image, "match: ", point(0, 60), 4, 1, scalar(0, 255, 0), 2, 0 );
    if(number_result == -1)
    puttext(hand_recognition_image, " ", point(120, 60), 4, 2, scalar(255, 0 ,0), 2, 0);
    else
    puttext(hand_recognition_image, number_str.str(), point(150, 60), 4, 2, scalar(255, 0 ,0), 2, 0);
    imshow("handrecognition", hand_recognition_image);
    imshow("hand_segment", hand_segment);
    /*一个循环中对有些变量进行初始化操作*/
    convex_number_above_point1 = 0;
    convex_number_above_point2 = 0;
    concave_number_above_point1 = 0;
    concave_number_above_point2 = 0;
    convex_assist_above_point1 = 0;
    convex_assist_above_point2 = 0;
    number_result = -1;
    recognition_flag = false;
    number_str.clear();
    waitkey(20);
    }
    }
    

    3 深度学习方法做手势识别

    3.1 经典的卷积神经网络

    卷积神经网络的优势就在于它能够从常见的视觉任务中自动学习目 标数据的特征, 然后将这些特征用于某种特定任务的模型。 随着时代的发展, 深度学习也形成了一些经典的卷积神经网络。

    3.2 yolo系列

    yolo 系列的网络模型最早源于 2016 年, 之后几年经过不断改进相继推出yolov2、 yolov3 等网络,直到今日yolov5也诞生了,不得不感慨一句,darknet是真的肝。

    最具代表性的yolov3的结构

    3.3 ssd

    ssd 作为典型的一阶段网络模型, 具有更高的操作性, 端到端的学习模式同样受到众多研究者的喜爱

    3.4 实现步骤

    3.4.1 数据集

    手势识别的数据集来自于丹成学长实验室,由于中国手势表示3的手势根据地区有略微差异,按照这个数据集的手势训练与测试即可。

    • 图像大小:100*100
    • 像素颜色空间:rgb种类
    • 图片种类:6 种(0,1,2,3,4,5)
    • 每种图片数量:200 张

    一共6种手势,每种手势200张图片,共1200张图片(100x100rgb)

    3.4.2 图像预处理

    实际图片处理展示:resize前先高斯模糊,提取边缘后可以根据实际需要增加一次中值滤波去噪:

    3.4.3 构建卷积神经网络结构

    使用tensorflow的框架,构建一个简单的网络结构

    dropout: 增加鲁棒性帮助正则化和避免过拟合

    一个相关的早期使用这种技术的论文((imagenet classification with deep convolutional neural networks, by alex krizhevsky, ilya sutskever, and geoffrey hinton (2012).))中启发性的dropout解释是:

    因为一个神经元不能依赖其他特定的神经元。因此,不得不去学习随机子集神经元间的鲁棒性的有用连接。换句话说。想象我们的神经元作为要给预测的模型,dropout是一种方式可以确保我们的模型在丢失一个个体线索的情况下保持健壮的模型。在这种情况下,可以说他的作用和l1和l2范式正则化是相同的。都是来减少权重连接,然后增加网络模型在缺失个体连接信息情况下的鲁棒性。在提高神经网络表现方面效果较好。

    3.4.4 实验训练过程及结果

    经过约4800轮的训练后,loss基本收敛,在0.6左右,在120份的测试样本上的模型准确率能够达到约96%

    3.5 关键代码

    # 作者:丹成学长 q746876041, 需要完整代码联系学长获取
    import tensorflow as tf
    image_size = 100
    num_channels = 1
    conv1_size = 4
    conv1_kernel_num = 8
    conv2_size = 2
    conv2_kernel_num = 16
    fc_size = 512
    output_node = 6
    def get_weight(shape, regularizer):
    w = tf.variable(tf.truncated_normal(shape,stddev=0.1))
    if regularizer != none: tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w)) 
    return w
    def get_bias(shape): 
    b = tf.variable(tf.zeros(shape))  
    return b
    def conv2d(x,w):  
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='same')
    def max_pool_8x8(x):  
    return tf.nn.max_pool(x, ksize=[1, 8, 8, 1], strides=[1, 4, 4, 1], padding='same')
    def max_pool_4x4(x):  
    return tf.nn.max_pool(x, ksize=[1, 4, 4, 1], strides=[1, 2, 2, 1], padding='same')
    def forward(x, train, regularizer):
    conv1_w = get_weight([conv1_size, conv1_size, num_channels, conv1_kernel_num], regularizer) 
    conv1_b = get_bias([conv1_kernel_num]) 
    conv1 = conv2d(x, conv1_w) 
    relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_b)) 
    pool1 = max_pool_8x8(relu1) 
    conv2_w = get_weight([conv2_size, conv2_size, conv1_kernel_num, conv2_kernel_num],regularizer) 
    conv2_b = get_bias([conv2_kernel_num])
    conv2 = conv2d(pool1, conv2_w) 
    relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_b))
    pool2 = max_pool_4x4(relu2)
    pool_shape = pool2.get_shape().as_list() 
    nodes = pool_shape[1] * pool_shape[2] * pool_shape[3] 
    reshaped = tf.reshape(pool2, [pool_shape[0], nodes]) 
    fc1_w = get_weight([nodes, fc_size], regularizer) 
    fc1_b = get_bias([fc_size]) 
    fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_w) + fc1_b) 
    if train: fc1 = tf.nn.dropout(fc1, 0.5)
    fc2_w = get_weight([fc_size, output_node], regularizer)
    fc2_b = get_bias([output_node])
    y = tf.matmul(fc1, fc2_w) + fc2_b
    return y 
    
    # 作者:丹成学长 q746876041, 需要完整代码联系学长获取
    import tensorflow as tf
    import numpy as np
    import gesture_forward
    import gesture_backward
    from image_processing import func5,func6
    import cv2
    def restore_model(testpicarr):
    with tf.graph().as_default() as tg:
    x = tf.placeholder(tf.float32,[
    1,
    gesture_forward.image_size,
    gesture_forward.image_size,
    gesture_forward.num_channels])    
    #y_ = tf.placeholder(tf.float32, [none, mnist_lenet5_forward.output_node])
    y = gesture_forward.forward(x,false,none)
    prevalue = tf.argmax(y, 1)
    variable_averages = tf.train.exponentialmovingaverage(gesture_backward.moving_average_decay)
    variables_to_restore = variable_averages.variables_to_restore()
    saver = tf.train.saver(variables_to_restore)
    with tf.session() as sess:
    ckpt = tf.train.get_checkpoint_state(gesture_backward.model_save_path)
    if ckpt and ckpt.model_checkpoint_path:
    saver.restore(sess, ckpt.model_checkpoint_path)
    #global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] 
    prevalue = sess.run(prevalue, feed_dict={x:testpicarr})
    return prevalue
    else:
    print("no checkpoint file found")
    return -1
    def application01():
    testnum = input("input the number of test pictures:")
    testnum = int(testnum)
    for i in range(testnum):
    testpic = input("the path of test picture:")
    img = func5(testpic)
    cv2.imwrite(str(i)+'ttt.jpg',img)   
    #        cv2.waitkey(0)
    #        cv2.destroyallwindows()
    img = img.reshape([1,100,100,1])
    img = img.astype(np.float32)
    img = np.multiply(img, 1.0/255.0)
    #        print(img.shape)
    #        print(type(img))        
    prevalue = restore_model(img)
    print ("the prediction number is:", prevalue)
    def application02():
    #vc = cv2.videocapture('testvideo.mp4')
    vc = cv2.videocapture(0)
    # 设置每秒传输帧数
    fps = vc.get(cv2.cap_prop_fps)
    # 获取视频的大小
    size = (int(vc.get(cv2.cap_prop_frame_width)),int(vc.get(cv2.cap_prop_frame_height)))
    # 生成一个空的视频文件
    # 视频编码类型
    # cv2.videowriter_fourcc('x','v','i','d') mpeg-4 编码类型
    # cv2.videowriter_fourcc('i','4','2','0') yuy编码类型
    # cv2.videowriter_fourcc('p','i','m','i') mpeg-1 编码类型
    # cv2.videowriter_fourcc('t','h','e','o') ogg vorbis类型,文件名为.ogv
    # cv2.videowriter_fourcc('f','l','v','1') flask视频,文件名为.flv
    #vw = cv2.videowriter('ges_pro.avi',cv2.videowriter_fourcc('x','v','i','d'), fps, size)
    # 读取视频第一帧的内容
    success, frame = vc.read()
    #    rows = frame.shape[0]    
    #    cols = frame.shape[1]
    #    t1 = int((cols-rows)/2)
    #    t2 = int(cols-t1)
    #    m = cv2.getrotationmatrix2d((cols/2,rows/2),90,1)
    #    frame = cv2.warpaffine(frame,m,(cols,rows))
    #    frame = frame[0:rows, t1:t2]
    #    cv2.imshow('sd',frame)
    #    cv2.waitkey(0)
    #    cv2.destroyallwindows()
    while success:
    #90度旋转        
    #        img = cv2.warpaffine(frame,m,(cols,rows))
    #        img = img[0:rows, t1:t2]
    img = func6(frame)
    img = img.reshape([1,100,100,1])
    img = img.astype(np.float32)
    img = np.multiply(img, 1.0/255.0)
    prevalue = restore_model(img)
    # 写入视频
    cv2.puttext(frame,"gesture:"+str(prevalue),(50,50),cv2.font_hershey_plain,2.0,(0,0,255),1)
    #vw.write(frame)
    cv2.imshow('gesture',frame)
    if cv2.waitkey(1) & 0xff == ord('q'):
    break
    # 读取视频下一帧的内容
    success, frame = vc.read()
    vc.release()
    cv2.destroyallwindows()    
    print('viedo app over!')
    def main():
    #application01()
    application02()
    if __name__ == '__main__':
    main()	
    

    4 实现手势交互

    我们还可以通过手势检测和识别,实现软件交互,学长录了一个视频,效果如下:

    以上就是python机器视觉之基于opencv的手势检测的详细内容,更多关于python opencv手势检测的资料请关注www.887551.com其它相关文章!