Home How to Set ROI for source and Destination Mat in OpenCVSharp
 I could not find the way to modify the specific area of the target Mat in openCVSharp. I am implementing this code in C#. I converted most of the code except these few lines in which part of the main image is replaced or modified by another image part. This code is actually placing a mask on face image. I will share the working code later when it completes. C++ Code // Warps and alpha blends triangular regions from img1 and img2 to img void warpTriangle(Mat &img1, Mat &img2, vector &t1, vector &t2) { Rect r1 = boundingRect(t1); Rect r2 = boundingRect(t2); // Offset points by left top corner of the respective rectangles vector t1Rect, t2Rect; vector t2RectInt; for(int i = 0; i < 3; i++) { t1Rect.push_back( Point2f( t1[i].x - r1.x, t1[i].y - r1.y) ); t2Rect.push_back( Point2f( t2[i].x - r2.x, t2[i].y - r2.y) ); t2RectInt.push_back( Point(t2[i].x - r2.x, t2[i].y - r2.y) ); // for fillConvexPoly } // Get mask by filling triangle Mat mask = Mat::zeros(r2.height, r2.width, CV_32FC3); fillConvexPoly(mask, t2RectInt, Scalar(1.0, 1.0, 1.0), 16, 0); // Apply warpImage to small rectangular patches Mat img1Rect; img1(r1).copyTo(img1Rect); Mat img2Rect = Mat::zeros(r2.height, r2.width, img1Rect.type()); applyAffineTransform(img2Rect, img1Rect, t1Rect, t2Rect); multiply(img2Rect,mask, img2Rect); multiply(img2(r2), Scalar(1.0,1.0,1.0) - mask, img2(r2)); img2(r2) = img2(r2) + img2Rect; } C# Code // Warps and alpha blends triangular regions from img1 and img2 to img void warpTriangle(ref Mat img1,ref Mat img2, List t1,List t2) { Rect r1 = Cv2.BoundingRect(t1); Rect r2 = Cv2.BoundingRect(t2); // Offset points by left top corner of the respective rectangles List t1Rect = new List(), t2Rect = new List(); List t2RectInt = new List(); for(int i = 0; i < 3; i++) { t1Rect.Add(new Point2f( t1[i].X - r1.X, t1[i].Y - r1.Y) ); t2Rect.Add(new Point2f( t2[i].X - r2.X, t2[i].Y - r2.Y) ); t2RectInt.Add(new OpenCvSharp.Point(t2[i].X - r2.X, t2[i].Y - r2.Y) ); // for fillConvexPoly } // Get mask by filling triangle Mat mask = Mat.Zeros(r2.Height, r2.Width, MatType.CV_32FC3); Cv2.FillConvexPoly(mask, t2RectInt, new Scalar(1.0, 1.0, 1.0), LineTypes.Link8, 0); // Apply warpImage to small rectangular patches Mat img1Rect = new Mat(img1,r1); //img1Rect.EmptyClone(); //img1(r1).copyTo(img1Rect); //img1.Clone(r1).CopyTo(img1Rect); Mat img2Rect = Mat.Zeros(r2.Height, r2.Width, img1Rect.Type()); applyAffineTransform(ref img2Rect,ref img1Rect, t1Rect, t2Rect); //img2Rect = img2Rect * mask; Cv2.Multiply(img2Rect,mask, img2Rect); //Mat roi = new Mat(img2,r2); //Cv2.Multiply(roi, new Scalar(1.0, 1.0, 1.0) - mask, roi); //roi = roi + img2Rect; //nn.CopyTo() //roi.CopyTo(img2); }