【问题标题】:OpenCV warping from one triangle to anotherOpenCV 从一个三角形扭曲到另一个三角形
【发布时间】:2012-04-11 06:05:13
【问题描述】:

我想将 OpenCV Mat 中的一个三角形映射到另一个三角形,就像 warpAffine 所做的一样(检查它here),但是对于三角形而不是四边形,以便在 Delaunay 三角剖分中使用它。

我知道有人可以使用口罩,但我想知道是否有更好的解决方案。

【问题讨论】:

    标签: opencv image-processing affinetransform


    【解决方案1】:

    我从我的帖子Warp one triangle to another using OpenCV ( C++ / Python ) 中复制了上面的图像和下面的 C++ 代码。下面代码中的 cmets 应该可以很好地了解正在发生的事情。有关更多详细信息和 python 代码,您可以访问上面的链接。 img1中三角形tri1内的所有像素都转换为img2中的三角形tri2。希望这会有所帮助。

    void warpTriangle(Mat &img1, Mat &img2, vector<Point2f> tri1, vector<Point2f> tri2)
    {
        // Find bounding rectangle for each triangle
        Rect r1 = boundingRect(tri1);
        Rect r2 = boundingRect(tri2);
    
       // Offset points by left top corner of the respective rectangles
       vector<Point2f> tri1Cropped, tri2Cropped;
       vector<Point> tri2CroppedInt;
       for(int i = 0; i < 3; i++)
       {
          tri1Cropped.push_back( Point2f( tri1[i].x - r1.x, tri1[i].y -  r1.y) );
          tri2Cropped.push_back( Point2f( tri2[i].x - r2.x, tri2[i].y - r2.y) );
    
          // fillConvexPoly needs a vector of Point and not Point2f
          tri2CroppedInt.push_back( Point((int)(tri2[i].x - r2.x), (int)(tri2[i].y - r2.y)) );
    
       }
    
       // Apply warpImage to small rectangular patches
       Mat img1Cropped;
       img1(r1).copyTo(img1Cropped);
    
       // Given a pair of triangles, find the affine transform.
       Mat warpMat = getAffineTransform( tri1Cropped, tri2Cropped );
    
       // Apply the Affine Transform just found to the src image
       Mat img2Cropped = Mat::zeros(r2.height, r2.width, img1Cropped.type());
       warpAffine( img1Cropped, img2Cropped, warpMat, img2Cropped.size(), INTER_LINEAR, BORDER_REFLECT_101);
    
       // Get mask by filling triangle
       Mat mask = Mat::zeros(r2.height, r2.width, CV_32FC3);
       fillConvexPoly(mask, tri2CroppedInt, Scalar(1.0, 1.0, 1.0), 16, 0);
    
      // Copy triangular region of the rectangular patch to the output image
      multiply(img2Cropped,mask, img2Cropped);
      multiply(img2(r2), Scalar(1.0,1.0,1.0) - mask, img2(r2));
      img2(r2) = img2(r2) + img2Cropped;
    
    }
    

    【讨论】:

      【解决方案2】:

      您应该使用getAffineTransform 找到变换,并使用warpAffine 应用它

      【讨论】:

      • 嗨 vasile,我会先使用 getAffineTransform(),然后使用 warpAffine(),但 warpAffine 会转换整个图像。我只想改变一个三角形。如果我可以将 ROI 设置为三角形就可以了,但我认为这个选项不存在。
      • 您必须在新图像中变形,然后使用蒙版进行复制。或修改 warpAffine 以满足您的需求
      • 我相信副本和掩码应该没问题。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多