赞
踩
背景:两张图片间有微小移位需要先对齐再计算,若无偏移可直接使用 cv2.subtract() 计算差异。
main.py目录创建一个img文件夹存放图片。
直接上脚本:
- import cv2
- import numpy as np
-
-
- def align_images(img1, img2, max_features=5000, good_match_percent=0.15):
- # Convert images to grayscale
- img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
- img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
-
- # Detect ORB features and compute descriptors
- orb = cv2.ORB_create(max_features)
- keypoints1, descriptors1 = orb.detectAndCompute(img1_gray, None)
- keypoints2, descriptors2 = orb.detectAndCompute(img2_gray, 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)
- matches = tuple(sorted(list(matches), key=lambda x: x.distance, reverse=False))
-
- # Remove not so good matches
- num_good_matches = int(len(matches) * good_match_percent)
- matches = matches[:num_good_matches]
-
- # 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 to align images
- height, width, channels = img2.shape
- img1_aligned = cv2.warpPerspective(img1, h, (width, height))
-
- return img1_aligned, img2
-
-
- def find_differences(img1, img2, threshold=30):
- # Convert images to grayscale
- img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
- img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
-
- # Compute absolute difference between the two images
- diff = cv2.absdiff(img1_gray, img2_gray)
-
- # Threshold the difference image
- _, thresh = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)
-
- return thresh
-
-
- if __name__ == '__main__':
- # Load images
- img1 = cv2.imread('img/img01.jpg')
- img2 = cv2.imread('img/img02.jpg')
-
- # Align the images
- img1_aligned, img2 = align_images(img1, img2)
-
- # Find differences between the aligned images
- differences = find_differences(img1_aligned, img2)
-
- # Save the result
- cv2.imwrite('img/differences.jpg', differences)
-
- # Show the result
- cv2.imshow('Differences', differences)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
这个脚本首先使用ORB特征检测器来检测两张图片的关键点,并计算描述符。然后,匹配特征点并使用RANSAC算法找到一个透视变换矩阵,以便将第一张图片与第二张图片对齐。最后,计算两张图片之间的差异,并将结果保存为一个新的图片。你也可以更改阈值参数以获得更好的差异检测结果。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。