opencv的初始化Mat、SVM、画多线条polylines

1、通过数组指针进行初始Mat变量:

例如:

        uchar arr[4][3] = { { 1, 1,1 },{ 2, 2,2 },{ 3, 3,3 },{ 4,4, 4 } };
	cv::Mat srcData(4, 3, CV_8UC1, arr);
	cout << "srcData=\n" << srcData << endl;

另一个:

	//这里通过指针赋值,耗时基本为零。data_ptr返回tensor第一个元素的地址。
	Mat dataimg = Mat(outimg.rows, outimg.cols, CV_32F, cup_outtensor.data_ptr());

2、SVM的使用:

其中opencv 2.4.xx版本跟opencv 3.xx的版本的在svm接口上又很大不同,不同点:

a、其中2.4.xx的SVM使用的是在cv命名空间下的CvSVM,而3.xx版本的是SVM使用的是在cv::ml命名空间下的SVM。

b、其中2.4.xx的SVM是不可以返回类别的概率值,而3.xx版本的是可以返回类别的probs值,其函数为:predict2().

  其它的参数设置、使用方法等基本都一样的。下面介绍的是3.xx的SVM版本代码例子:

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/ml.hpp>

int main()
{
    // 给训练数据打上标签,对应1类和-1类
    int Labels[4] = { 1, -1, -1, -1 };
    cv::Mat LabelsMat(4, 1, CV_32SC1, Labels);  // CV_32SC1: 32位有符号单通道矩阵

    // 设置训练数据的坐标,注意要和前面的Labels对应起来
    float TrainingData[4][2] = { {501., 10.}, {255., 10.}, {501., 255.}, {10., 501.} };
    cv::Mat TrainingDataMat(4, 2, CV_32F, TrainingData);

    // 初始化支持向量机,其要通过create创建,而且创建的对象是指针类型的。
    auto SVM = cv::ml::SVM::create();
    //ml::SVM* SVM = cv::ml::SVM::create(); //3.xx另一种表达方式
    //CvSVM SVM; //2.4.xx的svm对象创造,感觉更简单。
    SVM->setType(cv::ml::SVM::C_SVC);
    SVM->setKernel(cv::ml::SVM::LINEAR);
    SVM->setTermCriteria(cv::TermCriteria(cv::TermCriteria::MAX_ITER, 100, 1e-6));
    SVM->train(TrainingDataMat, cv::ml::ROW_SAMPLE, LabelsMat);

    // 初始化画布
    constexpr auto Width = 512, Height = 512;
    cv::Mat Image = cv::Mat::zeros(Height, Width, CV_8UC3);

    const cv::Vec3b Green(0, 255, 0), Blue(255, 0, 0);
    for (int i = 0; i < Image.rows; ++i)    // 遍历画布上的每个点
    {
        for (int j = 0; j < Image.cols; ++j)
        {
            cv::Mat SampleMat = (cv::Mat_<float>(1, 2) << j, i);
            auto Response = static_cast<int>(SVM->predict(SampleMat));  // 通过支持向量机预测该点的类别

            // 根据取得的类别来标记颜色
            if (Response == 1)
            {
                Image.at<cv::Vec3b>(i, j) = Green;
            }
            else if (Response == -1)
            {
                Image.at<cv::Vec3b>(i, j) = Blue;
            }
        }
    }

    // 在画布上画上训练数据所表示的点
    auto Thinckness = -1;
    cv::circle(Image, cv::Point(501, 10), 5, cv::Scalar(0, 0, 0), Thinckness);
    cv::circle(Image, cv::Point(255, 10), 5, cv::Scalar(255, 255, 255), Thinckness);
    cv::circle(Image, cv::Point(501, 255), 5, cv::Scalar(255, 255, 255), Thinckness);
    cv::circle(Image, cv::Point(10, 501), 5, cv::Scalar(255, 255, 255), Thinckness);

    Thinckness = 2;
    auto SV = SVM->getUncompressedSupportVectors(); // 获得支持向量
    for (int i = 0; i < SV.rows; ++i)
    {
        auto v = SV.ptr<float>(i);  // 给支持向量画上灰圈
        cv::circle(Image, cv::Point(static_cast<int>(v[0]), static_cast<int>(v[1])),
            6, cv::Scalar(128, 128, 128), Thinckness);
    }

    cv::imwrite("result.png", Image);
    cv::imshow("Result", Image);

    cv::waitKey();

    return 0;
}

3、polylines画多线条:

def plot_pose_box(image, Ps, pts68s, color=(40, 255, 0), line_width=2):
    ''' Draw a 3D box as annotation of pose. Ref:https://github.com/yinguobing/head-pose-estimation/blob/master/pose_estimator.py
    Args:
        image: the input image
        P: (3, 4). Affine Camera Matrix.
        kpt: (2, 68) or (3, 68)
    '''
    image = image.copy()
    if not isinstance(pts68s, list):
        pts68s = [pts68s]
    if not isinstance(Ps, list):
        Ps = [Ps]
    for i in range(len(pts68s)):
        pts68 = pts68s[i]
        #对角线长度
        llength = calc_hypotenuse(pts68)
        point_3d = build_camera_box(llength)
        P = Ps[i]

        # Map to 2d image points
        point_3d_homo = np.hstack((point_3d, np.ones([point_3d.shape[0], 1])))  # n x 4
        #把正常的三位点进行仿射变换,得到一个变换后的坐标,只取二维坐标
        point_2d = point_3d_homo.dot(P.T)[:, :2]

        point_2d[:, 1] = - point_2d[:, 1]
        #计算人脸框的底部方形的坐标均值,即中心坐标,其作用只是为了让框可以更靠近人脸中心,但是不会改变
        #其预测出的人脸姿态
        p1 = np.mean(point_2d[:4, :2], 0)
        #计算脸部最外围28个点的x、y偏移值,
        p2 = np.mean(pts68[:2, :27], 1)
        point_2d[:, :2] = point_2d[:, :2] - p1 +p2
        point_2d = np.int32(point_2d.reshape(-1, 2))

        # Draw all the lines。polylines是画所有的线
        cv2.polylines(image, [point_2d], True, color, line_width, cv2.LINE_AA)
        #还需要补充三条上下矩形框的连接线
        cv2.line(image, tuple(point_2d[1]), tuple(
            point_2d[6]), color, line_width, cv2.LINE_AA)
        cv2.line(image, tuple(point_2d[2]), tuple(
            point_2d[7]), color, line_width, cv2.LINE_AA)
        cv2.line(image, tuple(point_2d[3]), tuple(
            point_2d[8]), color, line_width, cv2.LINE_AA)

    return image

在人脸姿态估计的时候画出的结果为:

其中在C++使用的时候函数声明如下:

void cv::polylines  (   Mat &   img,
        const Point *const *    pts,
        const int *     npts,
        int     ncontours,
        bool    isClosed,
        const Scalar &      color,
        int     thickness = 1,
        int     lineType = LINE_8,
        int     shift = 0 
    )

使用的代码为:

void drawPoly()
{
    Mat img(600, 600, CV_8U, Scalar(0));
    Point points[2][4];
    points[0][0] = Point(100, 115);
    points[0][1] = Point(255, 135);
    points[0][2] = Point(140, 365);
    points[0][3] = Point(100, 300);
    points[1][0] = Point(300, 315);
    points[1][1] = Point(555, 335);
    points[1][2] = Point(340, 565);
    points[1][3] = Point(300, 500);
    //ppt[]要同时添加两个多边形顶点数组的地址头
    const Point* pts[] = {points[0],points[1]};
    //npts[]要定义每个多边形的定点数
    int npts[] = {4,4};
    polylines(img,pts,npts,2,true,Scalar(255),5,8,0);
    namedWindow("Poly");
    imshow("Poly", img);
    waitKey();
    fillPoly(img,pts,npts,2,Scalar(255),8,0,Point());
    imshow("Poly", img);
    waitKey();
}

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值