# -*- encoding=utf-8 -*- import cv2 import os import numpy as np MIN_MATCH_COUNT = 5 FLANN_INDEX_KDTREE = 0 detector = cv2.xfeatures2d.SURF_create() img1 = cv2.imread("1.jpg") #原图图片 demopoint, demoscript = detector.detectAndCompute(img1, None,useProvidedKeypoints=False) img = cv2.imread('22.jpg') #待矫正图片 imgpoint, imgscript = detector.detectAndCompute(img, None,useProvidedKeypoints=False) index_params = dict(algorithm=FLANN_INDEX_KDTREE, tree=5) search_params = dict(checks=50) flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(demoscript, imgscript, k=2) good = [] for m, n in matches: if m.distance < 0.7 * n.distance: good.append(m) if len(good) > MIN_MATCH_COUNT: src_pts = np.float32([demopoint[m.queryIdx].pt for m in good]).reshape(-1, 1, 2) dst_pts = np.float32([imgpoint[m.trainIdx].pt for m in good]).reshape(-1, 1, 2) H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2) dst = cv2.perspectiveTransform(pts, H) dst1 = np.float32([dst[0], dst[3], dst[1], dst[2]]) pts1 = np.float32([[0, 0], [w - 1, 0], [0, h - 1], [w - 1, h - 1]]) M = cv2.getPerspectiveTransform(dst1, pts1) #根据原图矫正后的图片 image = cv2.warpPerspective(img, M, (w, h)) cv2.imshow('', img) cv2.waitKey() cv2.destroyAllWindows()
利用surf特征矫正倾斜图像
最新推荐文章于 2022-10-10 10:00:00 发布