megrxu

Image Warping

Jul 28, 2017  #Image Process #Code 

Learn from others codes. About Image Warping.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Mat ImageWarping::PointVec2HomogeneousMat(const vector<Point2f>& pts)
{
  int num_pts = pts.size();
  Mat homMat(3, num_pts, CV_32FC1);
  for (int i = 0; i<num_pts; i++){
    homMat.at<float>(0, i) = pts[i].x;
    homMat.at<float>(1, i) = pts[i].y;
    homMat.at<float>(2, i) = 1.0;
  }
  return homMat;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
void ImageWarping::MorphPoints(const vector<Point2f>& srcPts1, const vector<Point2f>& srcPts2, vector<Point2f>& dstPts, float s)
{
  assert(srcPts1.size() == srcPts2.size());

  int num_pts = srcPts1.size();

  dstPts.resize(num_pts);
  for (int i = 0; i<num_pts; i++){
    dstPts[i].x = (1.0 - s) * srcPts1[i].x + s * srcPts2[i].x;
    dstPts[i].y = (1.0 - s) * srcPts1[i].y + s * srcPts2[i].y;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void ImageWarping::GetTriangleVertices(const Subdiv2D& sub_div, const vector<Point2f>& points, vector<Vec3i>& triangle_vertices)
{
  vector<Vec6f> triangles;
  sub_div.getTriangleList(triangles);

  int num_triangles = triangles.size();
  triangle_vertices.clear();
  triangle_vertices.reserve(num_triangles);
  for (int i = 0; i<num_triangles; i++){
    vector<Point2f>::const_iterator vert1, vert2, vert3;
    vert1 = find(points.begin(), points.end(), Point2f(triangles[i][0], triangles[i][1]));
    vert2 = find(points.begin(), points.end(), Point2f(triangles[i][2], triangles[i][3]));
    vert3 = find(points.begin(), points.end(), Point2f(triangles[i][4], triangles[i][5]));

    Vec3i vertex;
    if (vert1 != points.end() && vert2 != points.end() && vert3 != points.end()){
      vertex[0] = vert1 - points.begin();
      vertex[1] = vert2 - points.begin();
      vertex[2] = vert3 - points.begin();
      triangle_vertices.push_back(vertex);
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
void ImageWarping::TransTrianglerPoints(const vector<Vec3i>& triangle_vertices,const vector<Point2f>& points,vector<vector<Point2f>>& triangler_pts)
{
  int num_triangle = triangle_vertices.size();
  triangler_pts.resize(num_triangle);
  for (int i = 0; i<num_triangle; i++){
    vector<Point2f> triangle;
    for (int j = 0; j<3; j++){
      triangle.push_back(points[triangle_vertices[i][j]]);
    }
    triangler_pts[i] = triangle;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
void ImageWarping::PaintTriangles(Mat& img, const vector<vector<Point2f>>& triangles)
{
  int num_triangle = triangles.size();

  for (int i = 0; i<num_triangle; i++){
    vector<Point> poly(3);

    for (int j = 0; j<3; j++){
      poly[j] = Point(cvRound(triangles[i][j].x), cvRound(triangles[i][j].y));
    }
    fillConvexPoly(img, poly, Scalar(i + 1));
  }
}


See Also