模版匹配——在大量的图片中找到与模版相似的图像

2024-09-02 16:28

本文主要是介绍模版匹配——在大量的图片中找到与模版相似的图像,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

传统的特征匹配算法:

通过opencv自带的matchtemplate方法识别发现对形变、旋转的效果不是很好,后来尝试利用orb特征、sift特征匹配,由于车辆很多特征很相似,也不能很好的区分,如利用sift特征匹配效果如下:

代码:

import shutil
import cv2
import numpy as np
import osdef calculate_match_score(img1, img2):"""计算两张图像的匹配分数"""# 创建SIFT对象sift = cv2.SIFT_create()# 检测SIFT关键点和描述符keypoints1, descriptors1 = sift.detectAndCompute(img1, None)keypoints2, descriptors2 = sift.detectAndCompute(img2, None)if descriptors1 is None or descriptors2 is None:return 0  # 如果无法计算描述符,则匹配分数为0# 创建BFMatcher对象bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)matches = bf.match(descriptors1, descriptors2)# 计算匹配度(匹配点数量与总点数的比值)num_matches = len(matches)total_points = len(keypoints1) + len(keypoints2)if total_points > 0:match_score = num_matches / total_pointselse:match_score = 0return match_score * 1000def template_match_folder(template_img, folder):"""在文件夹中查找与模板图像匹配的图像"""all_img_list = {}folder_name = os.path.basename(template_img).split("_")[0]save_folder = os.path.join("G:", "ss", folder_name)os.makedirs(save_folder, exist_ok=True)for des_img_name in os.listdir(folder):des_img_path = os.path.join(folder, des_img_name)# 读取目标图像des_img = cv2.imread(des_img_path)if des_img is None:print(f"无法读取图像 {des_img_path}")continueheight, width = des_img.shape[:2]des_img_area = height * widthif des_img_area < 50 * 65:continue# 计算匹配分数match_score = calculate_match_score(template_img, des_img)if match_score > 200:all_img_list[des_img_name] = match_scoresave_img_path = os.path.join(save_folder, des_img_name)shutil.copy(des_img_path, save_img_path)return all_img_listdef template_folder_match_des_folder(template_folder, folder):"""遍历模板文件夹,匹配每个模板图像与目标文件夹中的图像"""for template_name in os.listdir(template_folder):template_path = os.path.join(template_folder, template_name)template_img = cv2.imread(template_path)if template_img is None:print(f"无法读取模板图像 {template_path}")continueall_img_list = template_match_folder(template_img, folder)with open("1.txt", "a", encoding="utf-8") as f:f.write(str(all_img_list))f.write("\n")# 主程序入口
template_folder = r"G:\dataset\M3FD\M3FD_Detection\templates"
folder = r"G:\dataset\M3FD\M3FD_Detection\cut_imgs"template_folder_match_des_folder(template_folder, folder)

效果: 

模版图像:

算法匹配结果:

模版图像:

算法匹配结果: 

深度学习匹配算法:

通过resne提取图像特征,计算余弦相似度。再映射至hsv和lab颜色空间计算颜色的相似度,共同去评估模版与目标的相似度。

代码:

import torch
import torchvision.transforms as transforms
from torchvision import models
from PIL import Image
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import cv2
import shutil
import os
import concurrent.futures
from tqdm import tqdm# 检查CUDA是否可用并选择设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
# 加载预训练的 ResNet 模型并将其移动到GPU
model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
model = model.to(device)  # 将模型移动到GPU
model.eval()  # 设置模型为评估模式# 定义图像预处理步骤
preprocess = transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])def preprocess_image(image):"""将图像预处理为模型输入格式"""if isinstance(image, str):image = Image.open(image).convert('RGB')if isinstance(image, np.ndarray):image = Image.fromarray(image)if isinstance(image, Image.Image):image = preprocess(image)image = image.unsqueeze(0).to(device)  # 增加一个批次维度并将图像移动到GPUreturn imageelse:raise TypeError("Unsupported image type: {}".format(type(image)))def get_features(image):"""提取图像特征"""image = preprocess_image(image)# 使用模型提取特征with torch.no_grad():features = model(image)return features.cpu().numpy().flatten()  # 将特征从GPU移动到CPU并展平def get_color_features(image):"""提取图像颜色直方图特征"""if isinstance(image, str):image = Image.open(image).convert('RGB')if isinstance(image, np.ndarray):image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)elif isinstance(image, Image.Image):image = np.array(image.convert('RGB'))else:raise TypeError("Unsupported image type: {}".format(type(image)))# 转换到 HSV 和 Lab 颜色空间hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)lab_image = cv2.cvtColor(image, cv2.COLOR_RGB2Lab)# 计算 HSV 颜色直方图hist_h = cv2.calcHist([hsv_image], [0], None, [256], [0, 256]).flatten()hist_s = cv2.calcHist([hsv_image], [1], None, [256], [0, 256]).flatten()hist_v = cv2.calcHist([hsv_image], [2], None, [256], [0, 256]).flatten()# 计算 Lab 颜色直方图hist_l = cv2.calcHist([lab_image], [0], None, [256], [0, 256]).flatten()hist_a = cv2.calcHist([lab_image], [1], None, [256], [-128, 128]).flatten()hist_b = cv2.calcHist([lab_image], [2], None, [256], [-128, 128]).flatten()# 计算颜色矩(均值和标准差)mean_hsv = np.mean(hsv_image, axis=(0, 1))std_hsv = np.std(hsv_image, axis=(0, 1))mean_lab = np.mean(lab_image, axis=(0, 1))std_lab = np.std(lab_image, axis=(0, 1))# 归一化直方图hist_h /= hist_h.sum() if hist_h.sum() > 0 else 1hist_s /= hist_s.sum() if hist_s.sum() > 0 else 1hist_v /= hist_v.sum() if hist_v.sum() > 0 else 1hist_l /= hist_l.sum() if hist_l.sum() > 0 else 1hist_a /= hist_a.sum() if hist_a.sum() > 0 else 1hist_b /= hist_b.sum() if hist_b.sum() > 0 else 1# 合并特征并进行标准化color_features = np.concatenate([hist_h, hist_s, hist_v, hist_l, hist_a, hist_b, mean_hsv, std_hsv, mean_lab, std_lab])color_features = (color_features - np.mean(color_features)) / (np.std(color_features) + 1e-6)  # 标准化return color_featuresdef compare_images(image1, image2):"""比较两张图像的相似性"""# 提取图像特征features1 = get_features(image1)features2 = get_features(image2)# 提取颜色特征color_features1 = get_color_features(image1)color_features2 = get_color_features(image2)similarity_reset = cosine_similarity([features1], [features2])[0][0]similarity_color = cosine_similarity([color_features1], [color_features2])[0][0]return similarity_reset, similarity_colordef calculate_match_score(img1, img2):"""计算SIFT匹配度"""# 创建SIFT对象sift = cv2.SIFT_create()# 检测SIFT关键点和描述符keypoints1, descriptors1 = sift.detectAndCompute(img1, None)keypoints2, descriptors2 = sift.detectAndCompute(img2, None)# 创建BFMatcher对象bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)matches = bf.match(descriptors1, descriptors2)# 计算匹配度(匹配点数量与总点数的比值)num_matches = len(matches)total_points = len(keypoints1) + len(keypoints2)if total_points > 100:match_score = num_matches / total_pointselse:match_score = 0return match_score * 1000def process_image_pair(template_img_path, des_img_path, save_folder):"""处理图像对并保存符合条件的图像"""template_img = cv2.imread(template_img_path)des_img = cv2.imread(des_img_path)height, width = des_img.shape[:2]des_img_area = height * widthif des_img_area < 50 * 65:return Nonesimilarity_reset_score, similarity_color_score = compare_images(template_img, des_img)if similarity_reset_score > 0.8 and similarity_color_score > 0.998:des_img_name = os.path.basename(des_img_path)save_img_path = os.path.join(save_folder, des_img_name)shutil.copy(des_img_path, save_img_path)return {des_img_name: similarity_reset_score}return Nonedef template_match_folder(template_path, folder, max_workers=8):"""处理文件夹中的所有图像"""all_img_list = {}template_img = cv2.imread(template_path)save_folder = os.path.join("G:\\fff", os.path.basename(template_path).split("_")[0])os.makedirs(save_folder, exist_ok=True)with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:futures = []for des_img_name in os.listdir(folder):des_img_path = os.path.join(folder, des_img_name)futures.append(executor.submit(process_image_pair, template_path, des_img_path, save_folder))for future in concurrent.futures.as_completed(futures):result = future.result()if result:all_img_list.update(result)return all_img_listdef template_folder_match_des_folder(template_folder, folder, max_workers=8):"""处理模板文件夹和目标文件夹"""for template_name in tqdm(os.listdir(template_folder)):template_path = os.path.join(template_folder, template_name)all_img_list = template_match_folder(template_path, folder, max_workers)with open("3.txt", "a", encoding="utf-8") as f:f.write(str(all_img_list))f.write("\n")# 示例路径(根据实际情况修改)
template_folder = r"G:\dataset\M3FD\M3FD_Detection\templates"
folder = r"G:\dataset\M3FD\M3FD_Detection\cut_imgs"# 调整 max_workers 的值以控制并行处理的数量
template_folder_match_des_folder(template_folder, folder, max_workers=4)

效果:

汽车所有模版图

所有的汽车图

算法得到的结果图:

 

 效果展示:

 

 

 

 

 

存在部分分类错误的情况:

 

优化建议:

黑车模版存在白车的情况,可以从颜色的特征进一步优化算法:

 

数据采用的是M3FD里面的车辆类别数据集

这篇关于模版匹配——在大量的图片中找到与模版相似的图像的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1130470

相关文章

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

使用Python实现base64字符串与图片互转的详细步骤

《使用Python实现base64字符串与图片互转的详细步骤》要将一个Base64编码的字符串转换为图片文件并保存下来,可以使用Python的base64模块来实现,这一过程包括解码Base64字符串... 目录1. 图片编码为 Base64 字符串2. Base64 字符串解码为图片文件3. 示例使用注意

Python中OpenCV与Matplotlib的图像操作入门指南

《Python中OpenCV与Matplotlib的图像操作入门指南》:本文主要介绍Python中OpenCV与Matplotlib的图像操作指南,本文通过实例代码给大家介绍的非常详细,对大家的学... 目录一、环境准备二、图像的基本操作1. 图像读取、显示与保存 使用OpenCV操作2. 像素级操作3.

C/C++的OpenCV 进行图像梯度提取的几种实现

《C/C++的OpenCV进行图像梯度提取的几种实现》本文主要介绍了C/C++的OpenCV进行图像梯度提取的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录预www.chinasem.cn备知识1. 图像加载与预处理2. Sobel 算子计算 X 和 Y

c/c++的opencv图像金字塔缩放实现

《c/c++的opencv图像金字塔缩放实现》本文主要介绍了c/c++的opencv图像金字塔缩放实现,通过对原始图像进行连续的下采样或上采样操作,生成一系列不同分辨率的图像,具有一定的参考价值,感兴... 目录图像金字塔简介图像下采样 (cv::pyrDown)图像上采样 (cv::pyrUp)C++ O

c/c++的opencv实现图片膨胀

《c/c++的opencv实现图片膨胀》图像膨胀是形态学操作,通过结构元素扩张亮区填充孔洞、连接断开部分、加粗物体,OpenCV的cv::dilate函数实现该操作,本文就来介绍一下opencv图片... 目录什么是图像膨胀?结构元素 (KerChina编程nel)OpenCV 中的 cv::dilate() 函

Python处理大量Excel文件的十个技巧分享

《Python处理大量Excel文件的十个技巧分享》每天被大量Excel文件折磨的你看过来!这是一份Python程序员整理的实用技巧,不说废话,直接上干货,文章通过代码示例讲解的非常详细,需要的朋友可... 目录一、批量读取多个Excel文件二、选择性读取工作表和列三、自动调整格式和样式四、智能数据清洗五、

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现

Java实现图片淡入淡出效果

《Java实现图片淡入淡出效果》在现代图形用户界面和游戏开发中,**图片淡入淡出(FadeIn/Out)**是一种常见且实用的视觉过渡效果,它可以用于启动画面、场景切换、轮播图、提示框弹出等场景,通过... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细