
点位偏差一直是一个很头疼的问题,但是由于摄像头和实际环境的局限性,我们不得不面对这个问题。对此,使用判别的方式进行一个仿射变换,是一种非常有效的方式,下图中图1是基准图,图2是目标图,图3是目标图仿射变换后得到的结果图。

可以看出效果非常的nice。
import cv2
import numpy as np
def get_good_match(des1,des2):
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(des1, des2, k=2)
    good = []
    for m, n in matches:
        if m.distance < 0.75 * n.distance:
            good.append(m)
    return good
def sift_kp(image):
    '''SIFT特征点检测'''
    height, width = image.shape[:2]
    size = (int(width * 0.2), int(height * 0.2))
    shrink = cv2.resize(image, size, interpolation=cv2.INTER_AREA)
    gray_image = cv2.cvtColor(shrink,cv2.COLOR_BGR2GRAY)
    sift = cv2.SIFT.create()
    kp, des = sift.detectAndCompute(gray_image, None)
    return kp,des
def siftImageAlignment(img1,img2):
    """
    img1: cv2.imread后读取的图片数组,标准图;
    img2: cv2.imread后读取的图片数组,测试图。
    函数作用:把img2配准到img1上,返回变换后的img2。注意:img1和img2的size一定要相同。
    """
    kp1,des1 = sift_kp(img1)
    kp2,des2 = sift_kp(img2)
    goodMatch = get_good_match(des1,des2)
    if len(goodMatch) > 4:
        ptsA= np.float32([kp1[m.queryIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
        ptsB = np.float32([kp2[m.trainIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
        ptsA = ptsA / 0.2
        ptsB = ptsB / 0.2
        ransacReprojThreshold = 4
        H, status =cv2.findHomography(ptsA,ptsB,cv2.RANSAC,ransacReprojThreshold)
        imgOut = cv2.warpPerspective(img2, H, (img1.shape[1],img1.shape[0]),flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
        return imgOut
    else:
        return img2
def cv_imread(file_path):
    """
    能读取中文路径的cv2读图函数。
    """
    cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
    return cv_img
def align(t0_path, t1_path):
    """
    测试函数,分别输入标准图和测试图的路径,输出变换后的图和对比图。
    """
    t0 = cv_imread(t0_path)
    t1 = cv_imread(t1_path)
    t1_img_align, _, _, ptsA, ptsB = siftImageAlignment(t0, t1)
    
    # # 把配准图写到本地
    # t1_new_bn = 'align_' + os.path.basename(t1_path)
    # cv2.imwrite('./pics/' + t1_new_bn, t1_img_align)
    # new_img = np.vstack((t0, t1, t1_img_align))
    # com_bn = 'compare_' + os.path.basename(t1_path)
    # cv2.imwrite('./pics/' + com_bn, new_img)
    
    return t1_img_align
if __name__ == "__main__":
    t0_path = r".\_1723957234138288128.jpg"
    t1_path = r".\1723957234138288128_20231115_200243.jpg"
    align(t0_path, t1_path) 
注意着仍然会出现一些不好的状况,但相似点寻找错误或者过小的时候。





![[清爽快捷] Ubuntu上多个版本的cuda切换](https://img-blog.csdnimg.cn/img_convert/5328d0cba3853dabffef701b095076e7.png)













