1. 程式人生 > >Learn OpenCV之WarpTriangle

Learn OpenCV之WarpTriangle

這篇文章將講述的是如何將一個圖片內的三角形內容對映到另一個圖片內的不同形狀的三角形內。

在圖形學的研究中,研究者常常進行三角形之間的變換操作,因為任意的3D表面都可以用多個三角形去近似表示。同樣的,圖片也可以分解成多個三角形來表示。但是在OpenCV中並沒有一個直接可以將三角形轉換為另一個三角形的函式。

下面將詳細的講述,如果將下圖中的左圖轉化成右圖。
在這裡插入圖片描述

在此之前,先介紹一個什麼是仿射變換。

什麼是仿射變換

仿射變換是一種將一個三個點的點集(例如三角形)變換到另一個三點點集的最簡單的變換方法。它包括平移、縮放、旋轉和剪下操作。下圖展示了對一個正方形做仿射變換的效果。但是仿射變換還是有一定侷限性的,它不能將一個正方形形變為任意的四邊形。一對平行的兩條邊經過放射變換後仍是平行的。
在這裡插入圖片描述


在OpenCV中,仿射變換可以用一個 2 × 3 2 \times 3 的矩陣表示,這個矩陣的前兩列表示旋轉、縮放、裁剪操作,後兩列表示平移操作。如下公式所示
S =
[ a b t
x
c d t y
]
S = \left[ \begin{matrix} a & b & t_{x} \\ c & d & t_{y} \end{matrix} \right ]

假設現在給定一點其座標為 ( x , y ) (x, y) ,通過上述仿射變換得到點座標 ( x t , y t ) (x_{t}, y_{t}) 如下式所示
[ x t y t ] = [ a b c d ] [ x y ] + [ t x t y ] \left[\begin{matrix}x_{t} \\ y_{t}\end{matrix}\right] =\left[\begin{matrix}a & b \\ c & d\end{matrix}\right] \left[\begin{matrix}x \\ y\end{matrix}\right]+ \left[\begin{matrix}t_{x} \\ t_{y}\end{matrix}\right]

使用OpenCV完成三角形的仿射變換

在OpenCV中,函式warpAffine可以對一張圖片進行仿射變換,但是不能直接對圖片中的三角形做仿射變換。為了完成三角形的仿射變換,可以在圖片中先找到三角形的外界矩形並將它從圖片中截取出來,然後將擷取的矩形進行仿射變換從而獲得輸出影象。*(其實可以不用擷取三角形的外接矩形也能完成,但是使用全圖會增加計算量。)*最後我們製作一個蒙版(mask),蒙版大小和仿射變換輸出影象大小一樣,蒙版裡需要進行輸出的三角形區域值為1其他為0,這樣將蒙版與輸出圖片相乘就可以得到最終的三角形輸出了。

下面進行程式碼的詳細講解,在這裡輸出圖片是一個全白的圖片,你也可以將仿射變換後的三角形放置在其他圖片中。

C++

// Read input image and convert to float
Mat img1 = imread("robot.jpg");
img1.convertTo(img1, CV_32FC3, 1/255.0);

// Output image is set to white
Mat img2 = Mat::ones(imgIn.size(), imgIn.type());
imgOut = Scalar(1.0, 1.0, 1.0);

// Input triangle
vector <Point2f> tri1;
tri1.push_back(Point2f(360, 200));
tri1.push_back(Point2f(60, 250));
tri1.push_back(Point2f(450, 400));

// Output triangle
vector <Point2f> tri2;
tri2.push_back(Point2f(400, 200));
tri2.push_back(Point2f(160, 270));
tri2.push_back(Point2f(400, 400));

Python

# Read input image
img1 = cv2.imread("robot.jpg")

# Output image is set to white
img2 = 255 * np.ones(img1.shape, dtype = img1.type)

# Define input and output triangles 
tri1 = np.float32([[[360,200], [60,250], [450,400]]])
tri2 = np.float32([[[400,200], [160,270], [400,400]]])

現在輸入輸出影象,還有要進行仿射變換的三角形已經完成定義了,下面開始進行三角形仿射變換的操作:

1.求三角形的外界矩形

這步可做可不做,主要是為了提高仿射變換的效率,減少計算量。

C++

// Find bounding rectangle for each triangle
Rect r1 = boundingRect(tri1);
Rect r2 = boundingRect(tri2);

Python

# Find bounding box. 
r1 = cv2.boundingRect(tri1)
r2 = cv2.boundingRect(tri2)
2.擷取外界矩形並修改三角形的座標值

因為要在上面獲得的外接矩形中進行仿射變換,所以原點從圖片的左上角點變成了外接矩形的左上角點,從而要修改三角形的三點座標。

C++

// Offset points by left top corner of the respective rectangles
vector<Point2f> tri1Cropped, tri2Cropped;
vector<Point2f> 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);

Python

# Offset points by left top corner of the 
# respective rectangles

tri1Cropped = []
tri2Cropped = []

for i in xrange(0, 3):
    tri1Cropped.append(((tri1[0][i][0] - r1[0]),(tri1[0][i][1] - r1[1])))
    tri2Cropped.append(((tri2[0][i][0] - r2[0]),(tri2[0][i][1] - r2[1])))

# Apply warpImage to small rectangular patches
img1Cropped = img1[r1[1]:r1[1] + r1[3], r1[0]:r1[0] + r1[2]]
3.獲取仿射變換矩陣

通過上述得到的輸入三角形的三個座標和輸出三角形的三個座標,可以計算出仿射變換要使用的仿射變換矩陣。

C++

// Given a pair of triangles, find the affine transform.
Mat warpMat = getAffineTransform(tri1Cropped, tri2Cropped);

Python

# Given a pair of triangles, find the affine transform.
warpMat = cv2.getAffineTransform(np.float32(tri1Cropped), np.float32(tri2Cropped))
4.對外接矩形做仿射變換

通過OpenCV中的warpAffine函式完成。

C++

// 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);

Python

# Apply the Affine Transform just found to the src image
img2Cropped = cv2.warpAffine(img1Cropped, warpMat, (r2[2], r2[3]), None, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101 ))
5.利用蒙版獲取最終的三角形仿射變換結果

蒙版可以先建立一個值全為0的圖片,然後利用fillConvexPoly函式將要獲取的三角形區域填充為1,最後將蒙版與上個步驟輸出的圖片結果相乘就可以得到對應區域的值了。

C++

// 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;

Python

# Get mask by filling triangle
mask = np.zeros((r2[3], r2[3], 3), dtype = np.float32)
cv2.fillConvexPoly(mask, np.int32(tri2Cropped), (1.0, 1.0, 1.0), 16, 0)

# Apply mask to cropped region
img2Cropped = img2Cropped * mask

# Copy triangular region of the rectangular patch to the output image
img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] = img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] * ( (1.0, 1.0, 1.0) - mask )
     
img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] = img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] + img2Cropped

到這裡三角形的仿射變換就完成了。

程式碼下載
原部落格-Warp one triangle to another using OpenCV ( C++ / Python )