トップ 差分 一覧 ソース 検索 ヘルプ RSS ログイン

PRG-py_panorama

簡易パノラマを OPENCV とpython です

# matching features of two images
import cv2
import sys
import scipy as sp
import numpy as np

if len(sys.argv) < 3:
   print 'usage: %s img1 img2' % sys.argv[0]
   sys.exit(1)

img1_path = sys.argv[1]
img2_path = sys.argv[2]

img1 = cv2.imread(img1_path, cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread(img2_path, cv2.IMREAD_GRAYSCALE)

# detector = cv2.ORB_create()
detector = cv2.AKAZE_create()

kp1, des1 = detector.detectAndCompute(img1, None)
kp2, des2 = detector.detectAndCompute(img2, None)

print '#keypoints in image1: %d, image2: %d' % (len(kp1), len(kp2))

# # descriptors

# match the keypoints
matcher = cv2.BFMatcher(cv2.NORM_HAMMING)
matches = matcher.match(des1, des2)

# visualize the matches
print '#matches:', len(matches)
dist = [m.distance for m in matches]

print 'distance: min: %.3f' % min(dist)
print 'distance: mean: %.3f' % (sum(dist) / len(dist))
print 'distance: max: %.3f' % max(dist)

# threshold: half the mean
thres_dist = (sum(dist) / len(dist)) * 0.5

# keep only the reasonable matches
sel_matches = [m for m in matches if m.distance < thres_dist]

print '#selected matches:', len(sel_matches)

# #####################################
# visualization
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#

view = sp.zeros((max(h1, h2), (w1 + w2), 3), sp.uint8)
# view = sp.zeros((max(int(h1*1.2), int(h2*1.2)), int((w1 + w2)*1.5), 3), sp.uint8)
# view = sp.zeros(((h1+ h2), w1 + w2, 3), sp.uint8)
  
## src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
## dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
src_pts = np.float32([ kp1[m.queryIdx].pt for m in sel_matches ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx].pt for m in sel_matches ]).reshape(-1,1,2)

## M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)
M, mask = cv2.findHomography(src_pts, dst_pts)
# matchesMask = mask.ravel().tolist()

## dst = cv2.warpPerspective(img1,mask,(h1*1.5,w1*1.1))
### dst = cv2.warpPerspective(img1,M,((h1*1.5).integer(),(w1*1.1).integer()))

# src1 = cv2.warpPerspective(img1,M,(w1,h1))
# dst2 = cv2.warpPerspective(img2,M,(w2,h2))
#
# src1 = cv2.warpPerspective(img1,M,(int(w1*1.5),int(h1*1.1)))
# dst2 = cv2.warpPerspective(img2,M,(int(w2*1.5),int(h2*1.1)))

src1 = cv2.warpPerspective(img1,M,(int(w1*1.5),int(h1*1.1)))

for yy in range(w2):
   for xx in range(h2):
src1[xx,yy] = img2[xx,yy]

## cv2.imshow("view", view)
cv2.imshow("view", src1)
## cv2.imshow("img1", img1)
## cv2.imshow("img2", img2)

## cv2.imshow("dest1", src1)
## cv2.imshow("dest2", dst2)
#
cv2.waitKey()