【问题标题】:Find Differences Between Images with OpenCV Python使用 OpenCV Python 查找图像之间的差异
【发布时间】:2021-04-05 13:06:33
【问题描述】:

如何检测下面两张图片之间的差异?

我已尝试对 2 个图像进行阈值化并应用按位 XOR 来查找差异,但仍然无法获得我正在寻找的结果。

图片 1

图片 2

【问题讨论】:

  • 您在寻找什么结果?最大的不同是中心区域被遮盖了,但也有更微妙的区域,比如图像顶部的橙色位。这两个图像也是 jpg,即使您将图像重新保存为 jpg 而没有进行任何修改,您也可以预期一些像素会有所不同。
  • 你试过什么?显示您的代码和结果。看起来他们需要先对齐。
  • @Reti43 推荐的图片格式是什么?
  • 这取决于你真正想做什么。如果是严格的逐像素比较(这意味着两张照片是对齐的,在相同的比例/旋转/闪电/等上,jpg 可能会导致问题。但是对于更聪明的算法,如下面的答案所示,这可能不是一个问题。

标签: python opencv computer-vision opencv-python


【解决方案1】:

您遇到的问题是您的图像在进行差异异或之前没有对齐。这是在 Python/OpenCV 中使用 ORB 特征匹配的一种方法。

输入 1:

输入 2:


import cv2
import numpy as np
 
MAX_FEATURES = 500
GOOD_MATCH_PERCENT = 0.15
  
def alignImages(im1, im2):

  # im2 is reference and im1 is to be warped to match im2
  # note: numbering is swapped in function
 
  # 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]
 
  # Draw top matches
  imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None)
  cv2.imwrite("circuit_matches.png", imMatches)
   
  # Extract location of good matches
  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
   
  # Find homography
  h, mask = cv2.findHomography(points1, points2, cv2.RANSAC)
 
  # Use homography
  height, width, channels = im2.shape
  im1Reg = cv2.warpPerspective(im1, h, (width, height))
   
  return im1Reg, h
 
 
if __name__ == '__main__':
   
  # Read reference image
  refFilename = "circuit1.jpg"
  print("Reading reference image : ", refFilename)
  imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR)
  hh, ww = imReference.shape[:2]
  
  # Read image to be aligned
  imFilename = "circuit2.jpg"
  print("Reading image to align : ", imFilename);  
  im = cv2.imread(imFilename, cv2.IMREAD_COLOR)
   
  # Aligned image will be stored in imReg. 
  # The estimated homography will be stored in h. 
  imReg, h = alignImages(im, imReference)
   
  # Print estimated homography
  print("Estimated homography : \n",  h)
  
  # Convert images to HSV and get saturation channel
  refSat = cv2.cvtColor(imReference, cv2.COLOR_BGR2HSV)[:,:,1]
  imSat = cv2.cvtColor(imReg, cv2.COLOR_BGR2HSV)[:,:,1]

  # Otsu threshold
  refThresh = cv2.threshold(refSat, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
  imThresh = cv2.threshold(imSat, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

  # apply morphology open and close
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
  refThresh = cv2.morphologyEx(refThresh, cv2.MORPH_OPEN, kernel, iterations=1)
  refThresh = cv2.morphologyEx(refThresh, cv2.MORPH_CLOSE, kernel, iterations=1).astype(np.float64)
  imThresh = cv2.morphologyEx(imThresh, cv2.MORPH_OPEN, kernel, iterations=1).astype(np.float64)
  imThresh = cv2.morphologyEx(imThresh, cv2.MORPH_CLOSE, kernel, iterations=1)
  
  # get absolute difference between the two thresholded images
  diff = np.abs(cv2.add(imThresh,-refThresh))
  
  # apply morphology open to remove small regions caused by slight misalignment of the two images
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (12,12))
  diff_cleaned = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel, iterations=1).astype(np.uint8)

  # Filter using contour area and draw bounding boxes that do not touch the sides of the image
  cnts = cv2.findContours(diff_cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  cnts = cnts[0] if len(cnts) == 2 else cnts[1]
  result = imReference.copy()
  for c in cnts:
      x,y,w,h = cv2.boundingRect(c)
      if x>0 and y>0 and x+w<ww-1 and y+h<hh-1:
        cv2.rectangle(result, (x, y), (x+w, y+h), (0, 0, 255), 2)

  # save images
  cv2.imwrite('circuit2_aligned.jpg', imReg)
  cv2.imwrite('circuit_diff.png', diff_cleaned)
  cv2.imwrite('circuit_result.png', result)

 # show images
  cv2.imshow('reference', imReference)
  cv2.imshow('image', im)
  cv2.imshow('image_aligned', imReg)
  cv2.imshow('refThresh', refThresh)
  cv2.imshow('imThresh', imThresh)
  cv2.imshow('diff', diff)
  cv2.imshow('diff_cleaned', diff_cleaned)
  cv2.imshow('result', result)
  cv2.waitKey()

ORB 比赛地点:

图像 2 与图像 1 对齐:

阈值差异:

显示不同区域的结果:

【讨论】:

  • 谢谢伙计。你是生命的救星。我最大的问题是过滤掉由顶部的白条产生的所有噪音,以及您已经用 3 个红色框成功识别它们的“棕色轨迹”。我会研究你的代码并理解你的方法。
  • 我没有对齐图像。那就是问题所在。你的答案非常有效。感谢您的帮助。我还尝试了其他示例图像,有些很好,有些显示多个误报。我会调查一下,看看我怎么能弄到它
猜你喜欢
  • 1970-01-01
  • 2013-06-15
  • 2016-02-07
  • 2016-09-21
  • 2019-10-04
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多