arucoモジュール で向きを正す

arucoモジュール で向きを正してみます。

本当はARとか、もっと高度なことをするためのライブラリ何でしょうけど、射影変換しやすそうなので、やってみました。

円の検出だとかは、円に似ているものを検出してしまうので、どうしても精度が落ちやすいのですが、このライブらいで生成されるマーカーは誤検出されにくそうです。

#!/usr/bin/env python
# -*- coding: utf-8 -*
import cv2
import numpy as np

aruco = cv2.aruco
dictionary = aruco.getPredefinedDictionary(aruco.DICT_4X4_50)

filename = 'DSC_3069.jpg'
#filename = 'DSC_3070.jpg'
img = cv2.imread(filename)
height, width, depth    = img.shape
div_n = 2
img = cv2.resize(img, (width/div_n, height/div_n))
height, width, depth    = img.shape

cv2.imwrite(filename+'.resize.png', img)

corners, ids, rejectedImgPoints = aruco.detectMarkers(img, dictionary)
print corners
print ids
#print rejectedImgPoints

# 配列を初期化
sPoints = [ [0]*2 ] * 4

for i, corner in enumerate( corners ):
    points = corner[0].astype(np.int32)
    cv2.polylines(img, [points], True, (0,255,0), 2)
    cv2.putText(img, str(ids[i][0]), tuple(points[0]), cv2.FONT_HERSHEY_PLAIN, 2,(0,0,255), 2)
    # 射影変換のために、1,0,2,3の順番に直す
    if ids[i][0] == 0:
        sPoints[1] = points[0]
    if ids[i][0] == 1:
        sPoints[0] = points[0]
    if ids[i][0] == 2:
        sPoints[2] = points[0]
    if ids[i][0] == 3:
        sPoints[3] = points[0]
print sPoints

cv2.imshow('drawDetectedMarkers', img)
cv2.imwrite(filename+'drawDetectedMarkers.png', img)

# 射影変換
# 右上、左上、左下、右下
rect = np.array([
    [940,100],
    [100,100],
    [100,1290],
    [940,1290],
])

pts1 = np.float32(sPoints)
pts2 = np.float32(rect)
print(pts1)
print(pts2)
M = cv2.getPerspectiveTransform(pts1,pts2)
img = cv2.warpPerspective(img,M,(width, height))
cv2.imshow('getPerspectiveTransform', img)
cv2.imwrite(filename+'getPerspectiveTransform.png', img)

cv2.waitKey(0)
cv2.destroyAllWindows()

f:id:pongsuke:20170609142607p:plain f:id:pongsuke:20170609142618p:plain f:id:pongsuke:20170609142630p:plain