opencv学习——cv2.findHomography()

# 第三个参数 Method used to computed a homography matrix. The following methods are possible:
        #0 - a regular method using all the points
        #CV_RANSAC - RANSAC-based robust method
        #CV_LMEDS - Least-Median robust method
        # 第四个参数取值范围在 1 到 10 , 绝一个点对的阈值。原图像的点经过变换后点与目标图像上对应点的误差
        # 超过误差就认为是 outlier
        # 返回值中 H 为变换矩阵。mask是掩模,online的点
        H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)

画出匹配点的连线,以及拼接图。
代码:

import cv2
import numpy as np

MIN_MATCH_COUNT = 10
img1 = cv2.imread('images/1.jpg')          # queryImage
img2 = cv2.imread('images/2.jpg')          # trainImage

def SIFT():
    # Initiate SIFT detector
    sift = cv2.xfeatures2d.SIFT_create()
    # find the keypoints and descriptors with SIFT
    kp1, des1 = sift.detectAndCompute(img2,None)
    kp2, des2 = sift.detectAndCompute(img1,None)
    # BFMatcher with default params
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(des1,des2, k=2)
    # Apply ratio test
    good = []
    for m,n in matches:
        if m.distance < 0.75*n.distance:

          good.append(m)
    # cv2.drawMatchesKnn expects list of lists as matches.
    good_2 = np.expand_dims(good, 1)
    matching = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good_2[:20],None, flags=2)

    if len(good)>MIN_MATCH_COUNT:
        # 获取关键点的坐标
        src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
        dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)

        H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)
        wrap = cv2.warpPerspective(img2, H, (img2.shape[1]+img2.shape[1] , img2.shape[0]+img2.shape[0]))
        wrap[0:img2.shape[0], 0:img2.shape[1]] = img1

        rows, cols = np.where(wrap[:,:,0] !=0)
        min_row, max_row = min(rows), max(rows) +1
        min_col, max_col = min(cols), max(cols) +1
        result = wrap[min_row:max_row,min_col:max_col,:]#去除黑色无用部分

        return matching, result

if __name__ == '__main__':
    matching, result = SIFT()
    cv2.imshow('img3.jpg',matching)
    cv2.imshow('result.jpg',result)
    cv2.waitKey(0)
    cv2.destroyAllWindows() 
    cv2.waitKey(1)
    cv2.waitKey(1)
    cv2.waitKey(1)
    cv2.waitKey(1)
### 计算机视觉课程设计使用 OpenCV 实现 #### 选择合适的主题 对于计算机视觉课程设计而言,选择一个既有趣又具有挑战性的课题至关重要。考虑到OpenCV的强大功能及其广泛应用范围[^1],可以选择诸如图像处理基础、特征提取与匹配、目标检测以及视频分析等领域作为研究方向。 #### 图像处理基础案例——灰度化转换 为了帮助理解基本概念并熟悉工具链操作,在此提供一段简单的Python代码片段用于将彩色图片转化为灰色调: ```python import cv2 def convert_to_grayscale(image_path): img = cv2.imread(image_path) gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) return gray_img if __name__ == "__main__": grayscale_image = convert_to_grayscale('example.jpg') cv2.imshow('Grayscale Image', grayscale_image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这段程序读取指定路径下的JPEG文件,并将其颜色空间由BGR转为GrayScale模式显示出来。 #### 特征点检测实例——SIFT算法应用 当涉及到更复杂的任务比如对象识别时,则可能需要用到一些特定的技术手段来增强系统的鲁棒性和准确性。下面给出了一种基于尺度不变特征变换(Scale-Invariant Feature Transform,SIFT)的方法来进行两幅不同视角下同一物体之间的对应关系查找: ```python import numpy as np import cv2 sift = cv2.SIFT_create() img1 = cv2.imread('object_1.png') # 查询图像 gray1= cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY) kp1, des1 = sift.detectAndCompute(gray1,None) FLANN_INDEX_KDTREE = 1 index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) search_params = dict(checks=50) flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(des1,kp2=kps_train,k=2) good_matches = [] for m,n in matches: if m.distance < 0.7*n.distance: good_matches.append(m) MIN_MATCH_COUNT = 10 if len(good_matches)>MIN_MATCH_COUNT: src_pts = np.float32([ kp1[m.queryIdx].pt for m in good_matches ]).reshape(-1,1,2) dst_pts = np.float32([ kps_train[m.trainIdx].pt for m in good_matches ]).reshape(-1,1,2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0) else: print ("Not enough matches are found - %d/%d" % (len(good_matches),MIN_MATCH_COUNT)) ``` 上述脚本利用了SIFT描述子计算两张照片间的相似之处,并通过RANSAC算法估计两者间最佳单应矩阵从而实现配准效果. #### 面部表情分类实践—深度学习模型集成 随着近年来人工智能技术的发展进步,越来越多的研究人员倾向于采用卷积神经网络(Convolutional Neural Networks,CNNs)解决实际问题。这里介绍如何借助预训练好的VGGFace模型快速搭建一个人脸情绪预测器: ```python from keras.preprocessing import image from keras_vggface.vggface import VGGFace from keras_vggface.utils import preprocess_input import numpy as np model = VGGFace(model='vgg16') def predict_emotion(face_image): face_image = cv2.resize(face_image,(224, 224)) x = image.img_to_array(face_image) x = np.expand_dims(x,axis=0) x = preprocess_input(x,version=1) preds = model.predict(x) emotion_labels=['Angry','Disgust','Fear','Happy','Sad','Surprise','Neutral'] predicted_label=np.argmax(preds[0]) confidence=preds[0][predicted_label]*100 result={ 'Emotion':emotion_labels[predicted_label], 'Confidence':'%.2f%%'%confidence} return result ``` 该段落说明了怎样加载预先训练过的权重参数并对输入的人脸ROI区域做出情感倾向评估.
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值