Python OpenCV ORB图像对齐的遮罩问题

时间:2019-03-05 22:20:03

标签: python opencv computer-vision template-matching orb

我正在尝试实现Python(3.7)OpenCV(3.4.3)ORB图像对齐。我通常使用ImageMagick进行大部分处理。但是我需要进行一些图像对齐,并尝试使用Python OpenCV ORB。我的脚本基于https://www.learnopencv.com/image-alignment-feature-based-using-opencv-c-python/上Satya Mallick的Learn OpenCV教程中的一个。

但是,我试图将其修改为使用刚性对齐方式而不是透视同源性,并使用蒙版过滤点以限制y值的差异,因为图像已经接近对齐了。

掩码方法取自https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_feature2d/py_matcher/py_matcher.html的最后一个示例中的FLANN对齐代码。

如果我删除matchesMask,它可以提供点过滤功能,那么我的脚本可以正常工作。 (我还有另外两个工作脚本。一个相似,但只是过滤点并忽略掩码。另一个基于ECC算法。)

但是,我想了解为什么下面的代码无法正常工作。

在我当前的Python Opencv版本中,我的遮罩结构是否不正确?

我得到的错误是:

Traceback (most recent call last):
  File "warp_orb_rigid2_filter.py", line 92, in <module>
    imReg, m = alignImages(im, imReference)
  File "warp_orb_rigid2_filter.py", line 62, in alignImages
    imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None, **draw_params)
SystemError: <built-in function drawMatches> returned NULL without setting an error


这是我的代码。第一个箭头显示创建遮罩的位置。第二个箭头显示我必须删除的行才能使脚本正常工作。但这会忽略我对点的过滤。

#!/bin/python3.7

import cv2
import numpy as np


MAX_FEATURES = 500
GOOD_MATCH_PERCENT = 0.15


def alignImages(im1, im2):

  # Convert images to grayscale
  im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
  im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)

  # Detect ORB features and compute descriptors.
  orb = cv2.ORB_create(MAX_FEATURES)
  keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)
  keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)

  # Match features.
  matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
  matches = matcher.match(descriptors1, descriptors2, None)

  # Sort matches by score
  matches.sort(key=lambda x: x.distance, reverse=False)

  # Remove not so good matches
  numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)
  matches = matches[:numGoodMatches]

  # Extract location of good matches and filter by diffy
  points1 = np.zeros((len(matches), 2), dtype=np.float32)
  points2 = np.zeros((len(matches), 2), dtype=np.float32)

  for i, match in enumerate(matches):
    points1[i, :] = keypoints1[match.queryIdx].pt
    points2[i, :] = keypoints2[match.trainIdx].pt

  # initialize empty arrays for newpoints1 and newpoints2 and mask
  newpoints1 = np.empty(shape=[0, 2])
  newpoints2 = np.empty(shape=[0, 2])
  matches_Mask = [0] * len(matches)

  # filter points by using mask    
  for i in range(len(matches)):
      pt1 = points1[i]
      pt2 = points2[i]
      pt1x, pt1y = zip(*[pt1])
      pt2x, pt2y = zip(*[pt2])
      diffy = np.float32( np.float32(pt2y) - np.float32(pt1y) )
      print(diffy)
      if abs(diffy) < 10.0:
        newpoints1 = np.append(newpoints1, [pt1], axis=0)
        newpoints2 = np.append(newpoints2, [pt2], axis=0)
        matches_Mask[i]=[1,0]  #<--- mask created
  print(matches_Mask)

  draw_params = dict(matchColor = (255,0,),
    singlePointColor = (255,255,0),
    matchesMask = matches_Mask, #<---- remove mask here
    flags = 0)

  # Draw top matches
  imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None, **draw_params)
  cv2.imwrite("/Users/fred/desktop/lena_matches.png", imMatches)


  # Find Affine Transformation
  # true means full affine, false means rigid (SRT)
  m = cv2.estimateRigidTransform(newpoints1,newpoints2,False)

  # Use affine transform to warp im1 to match im2
  height, width, channels = im2.shape
  im1Reg = cv2.warpAffine(im1, m, (width, height))

  return im1Reg, m


if __name__ == '__main__':

  # Read reference image
  refFilename = "/Users/fred/desktop/lena.png"
  print("Reading reference image : ", refFilename)
  imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR)

  # Read image to be aligned
  imFilename = "/Users/fred/desktop/lena_r1.png"
  print("Reading image to align : ", imFilename);  
  im = cv2.imread(imFilename, cv2.IMREAD_COLOR)

  print("Aligning images ...")
  # Registered image will be stored in imReg. 
  # The estimated transform will be stored in m. 
  imReg, m = alignImages(im, imReference)

  # Write aligned image to disk. 
  outFilename = "/Users/fred/desktop/lena_r1_aligned.jpg"
  print("Saving aligned image : ", outFilename); 
  cv2.imwrite(outFilename, imReg)

  # Print estimated homography
  print("Estimated Affine Transform : \n",  m)


这是我的两个图像:lena和lena旋转了1度。请注意,这些不是我的实际图像。这些图像没有大于10的diffy值,但是我的实际图像却有。

enter image description here

enter image description here

我正在尝试对齐并扭曲旋转后的图像以匹配原始的莉娜图像。

1 个答案:

答案 0 :(得分:2)

创建遮罩的方式不正确。它只需是带有单个数字的列表,每个数字都会告诉您是否要使用该特定功能匹配项。

因此,替换此行:

matches_Mask = [[0,0] for i in range(len(matches))]

与此:

matches_Mask = [0] * len(matches)

...所以:

# matches_Mask = [[0,0] for i in range(len(matches))]
matches_Mask = [0] * len(matches)

这将创建一个与匹配数一样长的0列表。最后,您需要使用单个值更改对掩码的写入:

  if abs(diffy) < 10.0:
    #matches_Mask[i]=[1,0]  #<--- mask created
    matches_Mask[i] = 1

我终于明白了:

Estimated Affine Transform :
 [[ 1.00001187  0.01598318 -5.05963793]
  [-0.01598318  1.00001187 -0.86121051]]

请注意,根据使用的匹配器,掩码的格式会有所不同。在这种情况下,您将使用蛮力匹配,因此掩码必须采用我刚刚描述的格式。

例如,如果您使用FLANN的knnMatch,则它将是列表的嵌套列表,每个元素都是一个k长的列表。例如,如果您有k=3和五个关键点,它将是一个包含五个元素的列表,每个元素都是一个包含三个元素的列表。子列表中的每个元素都描述了您要用于绘图的匹配项。