C++ 提取圖像ROI保存到Mat

只要給定待提取ROI的四個角點座標,利用OpenCV的透視變換計算出變換矩陣,就可以實現提取並保存到Mat;

void ls::getROI(cv::Mat &src, float vertices[8],cv::Mat &dst)
    {
        float w2 = sqrt(pow(vertices[0] - vertices[2], 2) + pow(vertices[1] - vertices[3] ,2 ));
        float h2 = sqrt(pow(vertices[0] - vertices[4], 2) + pow(vertices[1] - vertices[5] ,2));
        dst = cv::Mat::zeros(h2, w2, CV_8UC3);
        
        //__android_log_print(ANDROID_LOG_INFO, "SRC", "error%d", src.rows);
        
        
        // corners of destination image with the sequence [tl, tr, bl, br]
        vector<Point2f> dst_pts, img_pts;
        dst_pts.push_back(cv::Point(0, 0));
        dst_pts.push_back(cv::Point(w2 - 1, 0));
        dst_pts.push_back(cv::Point(0, h2 - 1));
        dst_pts.push_back(cv::Point(w2 - 1, h2 - 1));
        
        // corners of source image with the sequence [tl, tr, bl, br]
        img_pts.push_back(cv::Point(vertices[0], vertices[1]));
        img_pts.push_back(cv::Point(vertices[2],vertices[3]));
        img_pts.push_back(cv::Point(vertices[4],vertices[5]));
        img_pts.push_back(cv::Point(vertices[6], vertices[7]));
        
        
        
        // convert to original image scale
        //    for (size_t i = 0; i < img_pts.size(); i++) {
        //        img_pts[i].x *= scale;
        //        img_pts[i].y *= scale;
        //    }
        
        // get transformation matrix
        cv::Mat M_trans = getPerspectiveTransform(img_pts, dst_pts);
        
        // apply perspective transformation
        warpPerspective(src, dst, M_trans, dst.size());
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章