Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warp an image into a quad region of another image using OpenCV

I have an image and i know four coordinates of that image, now i just want to put another small image on the contour formed by these four points. This contour is almost a square. Is there a way to fill this contour points with the image?

I tried to create a rectangle but i can't create a rectangle using more than one point. I'm stuck. Can't find any solutions.

like image 466
Sagar Avatar asked Feb 09 '23 07:02

Sagar


1 Answers

I assume that you want to "warp" an image (let's call it img) into a quad placed in another image (let's call it canvas) -- i.e. you basically want to do this:

First, you need to find the transformation (matrix) T between the rectangular image (img) and the destination quad (let's call it warpedImg):

cv::Mat T = getPerspectiveTransform(imgCorners,     // std::vector<cv::Point2f> that contains img's vertices -- i.e. (0, 0) (0,img.rows) (img.cols, img.rows) (img.cols, 0)
                                    warpedCorners); // std::vector<cv::Point2f> that contains warpedImg's vertices

Then, you can use T to generate warpedImg from img:

cv::Mat warpedImg;
cv::warpPerspective(img, warpedImg, T, canvas.size());

Finally, to "paste" warpedImg onto canvas, you can first "mask" the quad region in canvas:

cv::fillConvexPoly(canvas, warpedCorners, cv::Scalar::all(0), CV_AA);

Then apply an "or" operation:

cv::bitwise_or(warpedImg, canvas, canvas);

That's it!

like image 134
maddouri Avatar answered Feb 10 '23 22:02

maddouri