匹配算法 python

1. 基于特征的匹配算法

1.1 SIFT(Scale-Invariant Feature Transform)

SIFT 是一种在尺度和旋转上不变的特征点检测算法,常用于图像匹配。

步骤

  1. 关键点检测:检测图像中的关键点,利用高斯差分(Difference of Gaussians, DoG)进行检测。
  2. 关键点描述:计算关键点周围的梯度方向直方图,形成特征向量。
  3. 关键点匹配:使用欧几里得距离或其他距离度量方法匹配两个图像中的特征向量。
1.2 ORB(Oriented FAST and Rotated BRIEF)

ORB 是一种基于 FAST 特征检测和 BRIEF 特征描述的快速特征匹配算法。

步骤

  1. 关键点检测:使用 FAST 算法检测关键点。
  2. 关键点描述:使用 BRIEF 描述符对关键点进行描述,同时加入方向信息。
  3. 关键点匹配:使用汉明距离进行特征向量的匹配。
1.1 SIFT(Scale-Invariant Feature Transform)
import cv2# 读取图像
img1 = cv2.imread('image1.jpg', 0)
img2 = cv2.imread('image2.jpg', 0)# 初始化 SIFT 检测器
sift = cv2.SIFT_create()# 检测关键点和计算描述子
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)# 使用 BFMatcher 进行匹配
bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
matches = bf.match(des1, des2)# 绘制匹配结果
img_matches = cv2.drawMatches(img1, kp1, img2, kp2, matches, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
cv2.imshow('Matches', img_matches)
cv2.waitKey(0)
cv2.destroyAllWindows()
1.2 ORB(Oriented FAST and Rotated BRIEF)
import cv2# 读取图像
img1 = cv2.imread('image1.jpg', 0)
img2 = cv2.imread('image2.jpg', 0)# 初始化 ORB 检测器
orb = cv2.ORB_create()# 检测关键点和计算描述子
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)# 使用 BFMatcher 进行匹配
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)# 绘制匹配结果
img_matches = cv2.drawMatches(img1, kp1, img2, kp2, matches, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
cv2.imshow('Matches', img_matches)
cv2.waitKey(0)
cv2.destroyAllWindows()

2. 基于相似度的匹配算法

2.1 余弦相似度(Cosine Similarity)

余弦相似度用于计算两个向量之间的夹角余弦值,常用于文本匹配和推荐系统。

公式
cosine_similarity ( A , B ) = A ⋅ B ∥ A ∥ ∥ B ∥ \text{cosine\_similarity}(A, B) = \frac{A \cdot B}{\|A\| \|B\|} cosine_similarity(A,B)=A∥∥BAB

2.2 皮尔逊相关系数(Pearson Correlation Coefficient)

皮尔逊相关系数用于度量两个变量之间的线性相关性。

公式
r = ∑ ( x i − x ‾ ) ( y i − y ‾ ) ∑ ( x i − x ‾ ) 2 ∑ ( y i − y ‾ ) 2 r = \frac{\sum (x_i - \overline{x})(y_i - \overline{y})}{\sqrt{\sum (x_i - \overline{x})^2 \sum (y_i - \overline{y})^2}} r=(xix)2(yiy)2 (xix)(yiy)

2.1 余弦相似度(Cosine Similarity)
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np# 定义两个向量
A = np.array([1, 2, 3])
B = np.array([4, 5, 6])# 计算余弦相似度
cos_sim = cosine_similarity([A], [B])
print("Cosine Similarity:", cos_sim[0][0])
2.2 皮尔逊相关系数(Pearson Correlation Coefficient)
import numpy as np# 定义两个向量
A = np.array([1, 2, 3])
B = np.array([4, 5, 6])# 计算皮尔逊相关系数
pearson_corr = np.corrcoef(A, B)[0, 1]
print("Pearson Correlation Coefficient:", pearson_corr)

3. 基于距离的匹配算法

3.1 欧几里得距离(Euclidean Distance)

欧几里得距离是最常见的距离度量方法,计算两个点之间的直线距离。

公式
d ( A , B ) = ∑ i = 1 n ( A i − B i ) 2 d(A, B) = \sqrt{\sum_{i=1}^{n} (A_i - B_i)^2} d(A,B)=i=1n(AiBi)2

3.2 曼哈顿距离(Manhattan Distance)

曼哈顿距离计算两个点在所有坐标轴上的距离之和。

公式
d ( A , B ) = ∑ i = 1 n ∣ A i − B i ∣ d(A, B) = \sum_{i=1}^{n} |A_i - B_i| d(A,B)=i=1nAiBi

3.1 欧几里得距离(Euclidean Distance)
import numpy as np# 定义两个点
A = np.array([1, 2, 3])
B = np.array([4, 5, 6])# 计算欧几里得距离
euclidean_dist = np.linalg.norm(A - B)
print("Euclidean Distance:", euclidean_dist)
3.2 曼哈顿距离(Manhattan Distance)
import numpy as np# 定义两个点
A = np.array([1, 2, 3])
B = np.array([4, 5, 6])# 计算曼哈顿距离
manhattan_dist = np.sum(np.abs(A - B))
print("Manhattan Distance:", manhattan_dist)

4. 深度学习匹配算法

4.1 Siamese Network

Siamese 网络使用两个相同的神经网络结构来提取输入对的特征,通过度量特征向量之间的距离进行匹配。

步骤

  1. 输入对:将两个输入(如图像对、文本对)分别输入到相同的神经网络中。
  2. 特征提取:通过共享权重的神经网络提取特征。
  3. 距离计算:计算两个特征向量之间的距离(如欧几里得距离、余弦相似度)。
  4. 分类决策:根据距离判断输入对是否匹配。
4.2 Triplet Loss

Triplet Loss 用于训练模型,使得正样本对之间的距离小于负样本对之间的距离。

公式
L = max ⁡ ( 0 , d ( a , p ) − d ( a , n ) + α ) L = \max(0, d(a, p) - d(a, n) + \alpha) L=max(0,d(a,p)d(a,n)+α)
其中, a a a 为 anchor, p p p 为正样本, n n n 为负样本, α \alpha α 为边距。

4.1 Siamese Network
import tensorflow as tf
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Lambda
from tensorflow.keras.models import Model
from tensorflow.keras import backend as K
import numpy as npdef build_siamese_model(input_shape):input = Input(shape=input_shape)x = Conv2D(64, (10, 10), activation='relu')(input)x = MaxPooling2D((2, 2))(x)x = Conv2D(128, (7, 7), activation='relu')(x)x = MaxPooling2D((2, 2))(x)x = Conv2D(128, (4, 4), activation='relu')(x)x = MaxPooling2D((2, 2))(x)x = Conv2D(256, (4, 4), activation='relu')(x)x = Flatten()(x)x = Dense(4096, activation='sigmoid')(x)return Model(input, x)def euclidean_distance(vects):x, y = vectssum_square = K.sum(K.square(x - y), axis=1, keepdims=True)return K.sqrt(K.maximum(sum_square, K.epsilon()))input_shape = (105, 105, 1)
left_input = Input(shape=input_shape)
right_input = Input(shape=input_shape)siamese_model = build_siamese_model(input_shape)encoded_l = siamese_model(left_input)
encoded_r = siamese_model(right_input)distance = Lambda(euclidean_distance, output_shape=lambda x: (x[0], 1))([encoded_l, encoded_r])
model = Model([left_input, right_input], distance)model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()# Dummy data for demonstration
data1 = np.random.random((10, 105, 105, 1))
data2 = np.random.random((10, 105, 105, 1))
labels = np.random.randint(2, size=(10, 1))model.fit([data1, data2], labels, epochs=5)
4.2 Triplet Loss
import tensorflow as tf
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.models import Model
from tensorflow.keras import backend as Kdef build_embedding_model(input_shape):input = Input(shape=input_shape)x = Conv2D(64, (3, 3), activation='relu')(input)x = MaxPooling2D((2, 2))(x)x = Conv2D(128, (3, 3), activation='relu')(x)x = MaxPooling2D((2, 2))(x)x = Flatten()(x)x = Dense(128, activation='sigmoid')(x)return Model(input, x)def triplet_loss(y_true, y_pred, alpha=0.2):anchor, positive, negative = y_pred[:, 0], y_pred[:, 1], y_pred[:, 2]pos_dist = K.sum(K.square(anchor - positive), axis=1)neg_dist = K.sum(K.square(anchor - negative), axis=1)loss = K.maximum(pos_dist - neg_dist + alpha, 0.0)return K.mean(loss)input_shape = (28, 28, 1)
anchor_input = Input(shape=input_shape)
positive_input = Input(shape=input_shape)
negative_input = Input(shape=input_shape)embedding_model = build_embedding_model(input_shape)encoded_anchor = embedding_model(anchor_input)
encoded_positive = embedding_model(positive_input)
encoded_negative = embedding_model(negative_input)merged_output = tf.stack([encoded_anchor, encoded_positive, encoded_negative], axis=1)
model = Model([anchor_input, positive_input, negative_input], merged_output)model.compile(loss=triplet_loss, optimizer='adam')
model.summary()# Dummy data for demonstration
data_anchor = np.random.random((10, 28, 28, 1))
data_positive = np.random.random((10, 28, 28, 1))
data_negative = np.random.random((10, 28, 28, 1))
labels = np.random.random((10, 1))model.fit([data_anchor, data_positive, data_negative], labels, epochs=5)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/850392.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

智能合约中断言失败

断言失败: 断言(assert)在智能合约中用于确保内部逻辑的一致性和正确性,但如果使用不当,确实可能导致意外的合约终止或资金锁定。这是因为assert主要用于检测程序内部的错误,例如算法错误或逻辑错误&#…

k8s小型实验模拟

(1)Kubernetes 区域可采用 Kubeadm 方式进行安装。(5分) (2)要求在 Kubernetes 环境中,通过yaml文件的方式,创建2个Nginx Pod分别放置在两个不同的节点上,Pod使用hostPat…

邬家桥公园

文|随意的风 原文地址 我游览过现存规模最大、保存最完整的皇家园林颐和园,瞻仰过拥有世界上最大祭天建筑群的天坛公园,那都是多年前的事情了。 邬家桥公园相比颐和园、天坛公园,气势雄伟倒谈不上。它没有西湖的水平如镜&#xff…

Java | Leetcode Java题解之第139题单词拆分

题目&#xff1a; 题解&#xff1a; public class Solution {public boolean wordBreak(String s, List<String> wordDict) {Set<String> wordDictSet new HashSet(wordDict);boolean[] dp new boolean[s.length() 1];dp[0] true;for (int i 1; i < s.len…

TCP和UDP通信中如何处理并发冲突

在处理TCP和UDP通信中的并发冲突时&#xff0c;我们可以采取多种策略来确保数据的准确传输和系统的稳定性。以下是对TCP和UDP在并发冲突处理方面的详细分析&#xff1a; TCP通信中的并发处理 TCP是一种面向连接的传输层协议&#xff0c;它通过建立可靠的连接来保证数据的完整…

JimuReport 积木报表 v1.7.52 版本发布,免费的低代码报表

项目介绍 一款免费的数据可视化报表工具&#xff0c;含报表和大屏设计&#xff0c;像搭建积木一样在线设计报表&#xff01;功能涵盖&#xff0c;数据报表、打印设计、图表报表、大屏设计等&#xff01; Web 版报表设计器&#xff0c;类似于excel操作风格&#xff0c;通过拖拽完…

智能变电站网络报文记录及故障录波分析装置

是基于Intel X86、PowerPC、FPGA等技术的高度集成化的硬件平台&#xff0c;采用了高性能CPU无风扇散热、网络数据采集、高速数据压缩存储加密等多种技术&#xff0c;实现了高性能计算、多端口同步高速数据采集、数据实时分析、大容量数据存储等功能。 ● 在满足工业标准的同时&…

数据结构 -- 树状数组

前言 树状数组或二叉索引树&#xff08;Binary Indexed Tree&#xff09;&#xff0c;又以其发明者命名为 Fenwick 树。其初衷是解决数据压缩里的累积频率的计算问题&#xff0c;现多用于高效计算数列的前缀和、区间和。它可以以 O(logn) 的时间得到任意前缀和。并同时支持在 …

Kali Linux 2024.2 释出

渗透测试发行版 Kali Linux 释出了最新的 2024.2。 主要新特性包括&#xff1a;桌面环境更新到 GNOME 46&#xff0c;Xfce 环境加入 HiDPI 模式&#xff0c;更新了网络侦察工具 AutoRecon&#xff0c;监视 Linux 进程的命令行工具 pspy&#xff0c;提取和显示 CVE 信息的 Splo…

项目验收总体计划书(实际项目验收原件参考Word)

测试目标&#xff1a;确保项目的需求分析说明书中的所有功能需求都已实现&#xff0c;且能正常运行&#xff1b;确保项目的业务流程符合用户和产品设计要求&#xff1b;确保项目的界面美观、风格一致、易学习、易操作、易理解。 软件全套文档过去进主页。 一、 前言 &#xff0…

WHAT - 富文本编辑器系列(二)- 表情包面板

目录 一、背景二、实践1. 安装 Tiptap2. 创建表情包面板组件3. 在 Tiptap 编辑器中集成表情包面板4. 样式调整5. 完整示例代码 三、自定义格式编码的表情1. 数据压缩和传输效率2. 兼容性和一致性3. 安全性和防篡改4. 特定功能需求5. 集成现有系统6. 示例 一、背景 在一个富文本…

day38 ● 理论基础 ● 509. 斐波那契数 ● 70. 爬楼梯 ● 746. 使用最小花费爬楼梯

509. 斐波那契数 斐波那契数 &#xff08;通常用 F(n) 表示&#xff09;形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始&#xff0c;后面的每一项数字都是前面两项数字的和。也就是&#xff1a; F(0) 0&#xff0c;F(1) 1 F(n) F(n - 1) F(n - 2)&#xff0c;其中 …

Unity 编辑器扩展,获取目录下所有的预制件

先看演示效果 实现方案 1创建几个用于测试的cube 2&#xff0c;创建一个Editor脚本 3&#xff0c;编写脚本内容 附上源码 using UnityEditor; using UnityEngine;public class GetPrefeb : EditorWindow {private string folderPath "Assets/Resources"; // 指定预…

[FSCTF 2023]Tea_apk

得到密文和密钥 import base64 from ctypes import c_uint32import libnumDELTA 0x9E3779B9def decrypt(v, n, k):rounds 6 int(52 / n)sum c_uint32(rounds * DELTA)y v[0].valuewhile rounds > 0:e (sum.value >> 2) & 3p n - 1while p > 0:z v[p …

matlab仿真教程要点和难点以及实际应用

Matlab仿真基础教程 1. 确定问题和目标 概述:明确你要解决的问题和仿真的目标。 参考:无直接参考数字,但这是仿真流程的第一步(参考文章3)。 2. 建立数学模型 概述:根据问题和目标,建立相应的数学模型。 参考:无直接参考数字,但数学模型是仿真的基础(参考文章3)…

Django 连接mysql数据库配置

1&#xff0c;提前创建注册的app1应用 Test/Test/settings.py python manage.py startapp app1 2&#xff0c;配置mysql数据库连接 Test/Test/settings.py DATABASES {default: {ENGINE: django.db.backends.mysql,# 数据库名字NAME: db1,# 连接mysql数据库用户名USER: ro…

Python 基于阿里云的OSS对象存储服务实现本地文件上云框架

Python 基于阿里云的OSS对象存储服务实现将文件上云框架 文章目录 Python 基于阿里云的OSS对象存储服务实现将文件上云框架一、前言二、阿里云配置1、获取用户AKEY和AKeySecret2、创建Bucket 三、Python 阿里云oss上云框架1、安装oss2依赖库2、阿里云oss python 一、前言 未来…

2024年CKA模拟系统制作 | step-by-step | 1、基础环境准备

目录 一、软件环境 二、虚拟网络环境准备 1、编辑虚拟网络 2、网络设置 三、新建虚拟主机 1、新建目录 2、新建虚拟主机 四、系统安装 1、装载系统镜像 2、开启虚拟机 3、选择语言 4、键盘选择 5、网络配置 6、代理设置 7、设置软件源 8、存储设置 9、名称设置 …

摆脱Jenkins - 使用google cloudbuild 部署 java service 到 compute engine VM

在之前 介绍 cloud build 的文章中 初探 Google 云原生的CICD - CloudBuild 已经介绍过&#xff0c; 用cloud build 去部署1个 spring boot service 到 cloud run 是很简单的&#xff0c; 因为部署cloud run 无非就是用gcloud 去部署1个 GAR 上的docker image 到cloud run 容…

本地部署 RAGFlow

本地部署 RAGFlow 0. RAGFlow 是什么?1. 安装 wsl-ubuntu2. (可选)配置清华大学软件源3. 系统更新和安装构建工具4. 安装 Miniconda35. 安装 CUDA Toolkit6. 安装 git lfs7. 配置 Hugging Face 的缓存路径8. 配置 vm.max_map_count9. 安装 Docker Engine10. 安装 nginx11. 本地…