python提取图片特征并保存文件,匹配图片

方案一:采用sift算法提取特征并保存,用最近邻算法匹配最合适的图片

1.提取特征值并保存.npy文件, feature.py

import cv2

import numpy as np

from os import walk

from os.path import join

def create_descriptors(folder):

  files = []

  for (dirpath, dirnames, filenames) in walk(folder):

    files.extend(filenames)

  for f in files:

    if '.jpg' in f:

      save_descriptor(folder, f, cv2.xfeatures2d.SIFT_create())

def save_descriptor(folder, image_path, feature_detector):

  # 判断图片是否为npy格式

  if image_path.endswith("npy"):

    return

  # 读取图片并检查特征

  img = cv2.imread(join(folder,image_path), 0)

  keypoints, descriptors = feature_detector.detectAndCompute(img, None)

  # 设置文件名并将特征数据保存到npy文件

  descriptor_file = image_path.replace("jpg", "npy")

  np.save(join(folder, descriptor_file), descriptors)

if __name__=='__main__':

  path = './test' # 文件夹路径

  create_descriptors(path)

2.对比图片,匹配最佳图片 main.py

from os.path import join

from os import walk

import numpy as np

import cv2

query = cv2.imread('a.jpg', 0)

folder = './test'

descriptors = []

# 获取特征数据文件名

for (dirpath, dirnames, filenames) in walk(folder):

  for f in filenames:

    if f.endswith("npy"):

      descriptors.append(f)

  print(descriptors)

# 使用SIFT算法检查图像的关键点和描述符

sift = cv2.xfeatures2d.SIFT_create()

query_kp, query_ds = sift.detectAndCompute(query, None)

# 创建FLANN匹配器

index_params = dict(algorithm=0, trees=5)

search_params = dict(checks=50)

flann = cv2.FlannBasedMatcher(index_params, search_params)

potential_culprits = {}

for d in descriptors:

  # 将图像query与特征数据文件的数据进行匹配

  matches = flann.knnMatch(query_ds, np.load(join(folder, d)), k=2)

  # 清除错误匹配

  good = []

  for m, n in matches:

    if m.distance < 0.7 * n.distance:

      good.append(m)

  # 输出每张图片与目标图片的匹配数目

  print("img is %s ! matching rate is (%d)" % (d, len(good)))

  potential_culprits[d] = len(good)

# 获取最多匹配数目的图片

max_matches = None

potential_suspect = None

for culprit, matches in potential_culprits.items():

  if max_matches == None or matches > max_matches:

    max_matches = matches

    potential_suspect = culprit

print("potential suspect is %s" % potential_suspect.replace("npy", "").upper())

方案二:采用orb算法提取保存特征,并用最近邻匹配最合适的图片

1.提取特征值并保存.npy文件, feature.py

import cv2

import numpy as np

from os import walk

from os.path import join

def create_descriptors(folder):

  files = []

  for (dirpath, dirnames, filenames) in walk(folder):

    files.extend(filenames)

  for f in files:

    if '.jpg' in f:

      save_descriptor(folder, f, cv2.ORB_create())

def save_descriptor(folder, image_path, feature_detector):

  # 判断图片是否为npy格式

  if image_path.endswith("npy"):

    return

  # 读取图片并检查特征

  img = cv2.imread(join(folder,image_path), 0)

  keypoints, descriptors = feature_detector.detectAndCompute(img, None)

  # 设置文件名并将特征数据保存到npy文件

  descriptor_file = image_path.replace("jpg", "npy")

  np.save(join(folder, descriptor_file), descriptors)

if __name__=='__main__':

  path = './test' # 文件夹路径

  create_descriptors(path)

2.对比图片,匹配最佳图片 main.py

from os.path import join

from os import walk

import numpy as np

import cv2

query = cv2.imread('a.jpg', 0)

folder = './test'

descriptors = []

# 获取特征数据文件名

for (dirpath, dirnames, filenames) in walk(folder):

  for f in filenames:

    if f.endswith("npy"):

      descriptors.append(f)

  print(descriptors)

# 使用ORB算法检查图像的关键点和描述符

sift = cv2.ORB_create()

query_kp, query_ds = sift.detectAndCompute(query, None)

# 创建FLANN匹配器

index_params = dict(algorithm=6, table_number=12, key_size=12, multi_probe_level=2)

search_params = dict(checks=50)

flann = cv2.FlannBasedMatcher(index_params, search_params)

potential_culprits = {}

for d in descriptors:

  # 将图像query与特征数据文件的数据进行匹配

  matches = flann.knnMatch(query_ds, np.load(join(folder, d)), k=2)

  # 清除错误匹配

  good = []

  for m, n in matches:

    if m.distance < 0.4 * n.distance:

      good.append(m)

  # 输出每张图片与目标图片的匹配数目

  print("img is %s ! matching rate is (%d)" % (d, len(good)))

  potential_culprits[d] = len(good)

# 获取最多匹配数目的图片

max_matches = None

potential_suspect = None

for culprit, matches in potential_culprits.items():

  if max_matches == None or matches > max_matches:

    max_matches = matches

    potential_suspect = culprit

print("potential suspect is %s" % potential_suspect.replace("npy", "").upper())

你可能感兴趣的:(python,开发语言)