opencv中應用ArUco標記的AR

先解釋什麼是ArUco標記,然後怎麼用ArUco來做簡單的AR任務。

ArUco標記已經被應用在相機姿態估計,相機校準等方面。

什麼是ArUco標記

ArUco標記是2014年S.Garrido-Jurado開發出來的。

ArUco標記是一個基準點,其被放置在對象上或場景中。

一個ArUco標記外圍都有一組黑色邊框,同時內部有著確定該標記ID的二維矩陣組合而成。黑色的邊框能加速標記在圖像中的檢測速度,內部的二維編碼能唯一識別該標記,同時進行錯誤檢測和錯誤修復。標記的大小確定了內部矩陣的大小,例如4x4大小的標記有16個bit(5x5就有25bits?)。

一般是打印這些ArUco標記,放在真實世界中,然後拍照,檢測這些標記。

用OpenCV產生ArUco標記

可以使用opencv容易產生標記。opencv的aruco模塊有25個預定義字典。

所有標記都包含相同的大小(4x4,5x5,6x6,7x7)。可以用getPredefinedDictionary函數來加載250個標記的字典。python代碼如下:

<code>import cv2 as cv
import numpy as np

# Load the predefined dictionary
dictionary = cv.aruco.Dictionary_get(cv.aruco.DICT_6X6_250)

# Generate the marker
markerImage = np.zeros((200, 200), dtype=np.uint8)/<code>
<code>markerImage = cv.aruco.drawMarker(dictionary, 33, 200, markerImage, 1);
cv.imwrite("marker33.png", markerImage);/<code>

檢測ArUco標記

<code>#Load the dictionary that was used to generate the markers.
dictionary = cv.aruco.Dictionary_get(cv.aruco.DICT_6X6_250)

# Initialize the detector parameters using default values
parameters = cv.aruco.DetectorParameters_create()

# Detect the markers in the image
markerCorners, markerIds, rejectedCandidates = cv.aruco.detectMarkers(frame, dictionary, parameters=parameters)/<code>

detectMarkers函數的第一個參數是帶有標記的圖像,第二個參數是產生標記的字典,

實際應用

<code># Calculate Homography
h, status = cv.findHomography(pts_src, pts_dst)

# Warp source image to destination based on homography
warped_image = cv.warpPerspective(im_src, h, (frame.shape[1],frame.shape[0]))

# Prepare a mask representing region to copy from the warped image into the original frame.
mask = np.zeros([frame.shape[0], frame.shape[1]], dtype=np.uint8);
cv.fillConvexPoly(mask, np.int32([pts_dst_m]), (255, 255, 255), cv.LINE_AA);

# Erode the mask to not copy the boundary effects from the warping
element = cv.getStructuringElement(cv.MORPH_RECT, (3,3));
mask = cv.erode(mask, element, iterations=3);


# Copy the mask into 3 channels.
warped_image = warped_image.astype(float)
mask3 = np.zeros_like(warped_image)
for i in range(0, 3):
  mask3[:,:,i] = mask/255

# Copy the masked warped image into the original frame in the mask region.
warped_image_masked = cv.multiply(warped_image, mask3)
frame_masked = cv.multiply(frame.astype(float), 1-mask3)
im_out = cv.add(warped_image_masked, frame_masked)/<code>

這個實例是把相框中的圖像替換為了另外圖片。就是利用檢測aruco標記確定座標來實現的。


opencv中應用ArUco標記的AR


分享到:


相關文章: