点击上方“小白学视觉”,选择加"星标"或“置顶

重磅干货,第一时间送达

基于OpenCV实现SIFT特征提取与BOW(Bag of Word)生成向量数据,然后使用sklearn的线性SVM分类器训练模型,实现图像分类预测。实现基于词袋模型的图像分类预测与搜索,大致要分为如下四步:

1.特征提取与描述生成

这里选择SIFT特征,SIFT特征具有放缩、旋转、光照不变性,同时兼有对几何畸变,图像几何变形的一定程度的鲁棒性,使用Python OpenCV扩展模块中的SIFT特征提取接口,就可以提取图像的SIFT特征点与描述子。

2.词袋生成

词袋生成,是基于描述子数据的基础上,生成一系列的向量数据,最常见就是首先通过K-Means实现对描述子数据的聚类分析,一般会分成100个聚类、得到每个聚类的中心数据,就生成了100 词袋,根据每个描述子到这些聚类中心的距离,决定了它属于哪个聚类,这样就生成了它的直方图表示数据。

3.SVM分类训练与模型生成

使用SVM进行数据的分类训练,得到输出模型,这里通过sklearn的线性SVM训练实现了分类模型训练与导出。

4.模型使用与预测

加载预训练好的模型,使用模型在测试集上进行数据预测,测试表明,对于一些简单的图像分类与相似图像预测都可以获得比较好的效果。

完整步骤图示如下:

其中SIFT特征提取算法主要有如下几步:

1.构建高斯金子塔图像,寻找极值点 2.极值点亚像素级别定位 3.图像梯度与角度直方图建立 4.特征描述子建立

K-Means聚类方法 - 参见公众号以前的文章即可

OpenCV中KMeans算法介绍与应用

代码实现,特征提取与训练模型导出

import cv2
import imutils
import numpy as np
import os
from sklearn.svm import LinearSVC
from sklearn.externals import joblib
from scipy.cluster.vq import *
from sklearn.preprocessing import StandardScaler
# Get the training classes names and store them in a list
train_path = "dataset/train/"
training_names = os.listdir(train_path)
# Get all the path to the images and save them in a list
# image_paths and the corresponding label in image_paths
image_paths = []
image_classes = []
class_id = 0
for training_name in training_names:dir = os.path.join(train_path, training_name)class_path = imutils.imlist(dir)image_paths += class_pathimage_classes += [class_id] * len(class_path)class_id += 1
# 创建SIFT特征提取器
sift = cv2.xfeatures2d.SIFT_create()
# 特征提取与描述子生成
des_list = []
for image_path in image_paths:im = cv2.imread(image_path)im = cv2.resize(im, (300, 300))kpts = sift.detect(im)kpts, des = sift.compute(im, kpts)des_list.append((image_path, des))print("image file path : ", image_path)
# 描述子向量
descriptors = des_list[0][1]
for image_path, descriptor in des_list[1:]:descriptors = np.vstack((descriptors, descriptor))
# 100 聚类 K-Means
k = 100
voc, variance = kmeans(descriptors, k, 1)
# 生成特征直方图
im_features = np.zeros((len(image_paths), k), "float32")
for i in range(len(image_paths)):words, distance = vq(des_list[i][1], voc)for w in words:im_features[i][w] += 1
# 实现动词词频与出现频率统计
nbr_occurences = np.sum((im_features > 0) * 1, axis=0)
idf = np.array(np.log((1.0 * len(image_paths) + 1) / (1.0 * nbr_occurences + 1)), 'float32')
# 尺度化
stdSlr = StandardScaler().fit(im_features)
im_features = stdSlr.transform(im_features)
# Train the Linear SVM
clf = LinearSVC()
clf.fit(im_features, np.array(image_classes))
# Save the SVM
print("training and save model...")
joblib.dump((clf, training_names, stdSlr, k, voc), "bof.pkl", compress=3)

在训练图像上的运行输出:

"C:\Program Files\Python\Python36\python.exe" D:/python/image_classification/feature_detection.py
image file path :  dataset/train/aeroplane\1.jpg
image file path :  dataset/train/aeroplane\10.jpg
image file path :  dataset/train/aeroplane\11.jpg
image file path :  dataset/train/aeroplane\12.jpg
image file path :  dataset/train/aeroplane\13.jpg
image file path :  dataset/train/aeroplane\14.jpg
image file path :  dataset/train/aeroplane\15.jpg
image file path :  dataset/train/aeroplane\16.jpg
image file path :  dataset/train/aeroplane\17.jpg
image file path :  dataset/train/aeroplane\2.jpg
image file path :  dataset/train/aeroplane\3.jpg
image file path :  dataset/train/aeroplane\4.jpg
image file path :  dataset/train/aeroplane\5.jpg
image file path :  dataset/train/aeroplane\6.jpg
image file path :  dataset/train/aeroplane\7.jpg
image file path :  dataset/train/aeroplane\8.jpg
image file path :  dataset/train/aeroplane\9.jpg
image file path :  dataset/train/bicycle\1.jpg
image file path :  dataset/train/bicycle\10.jpg
image file path :  dataset/train/bicycle\11.jpg
image file path :  dataset/train/bicycle\12.jpg
image file path :  dataset/train/bicycle\13.jpg
image file path :  dataset/train/bicycle\14.JPG
image file path :  dataset/train/bicycle\15.png
image file path :  dataset/train/bicycle\16.jpg
image file path :  dataset/train/bicycle\17.jpg
image file path :  dataset/train/bicycle\2.jpg
image file path :  dataset/train/bicycle\3.jpg
image file path :  dataset/train/bicycle\4.png
image file path :  dataset/train/bicycle\5.jpg
image file path :  dataset/train/bicycle\6.jpg
image file path :  dataset/train/bicycle\7.jpg
image file path :  dataset/train/bicycle\8.JPG
image file path :  dataset/train/bicycle\9.jpg
image file path :  dataset/train/car\1.jpg
image file path :  dataset/train/car\10.jpg
image file path :  dataset/train/car\11.jpg
image file path :  dataset/train/car\12.jpg
image file path :  dataset/train/car\13.jpg
image file path :  dataset/train/car\14.jpg
image file path :  dataset/train/car\15.jpg
image file path :  dataset/train/car\16.jpg
image file path :  dataset/train/car\17.jpg
image file path :  dataset/train/car\2.jpeg
image file path :  dataset/train/car\3.jpg
image file path :  dataset/train/car\4.jpg
image file path :  dataset/train/car\5.jpg
image file path :  dataset/train/car\6.jpg
image file path :  dataset/train/car\7.jpg
image file path :  dataset/train/car\8.jpg
image file path :  dataset/train/car\9.jpg
training and save model...

程序测试

import os
import imutils
import cv2 as cv
import numpy as np
from sklearn.externals import joblib
from scipy.cluster.vq import *
# Load the classifier, class names, scaler, number of clusters and vocabulary
clf, classes_names, stdSlr, k, voc = joblib.load("bof.pkl")
# Create feature extraction and keypoint detector objects
sift = cv.xfeatures2d.SIFT_create()
def predict_image(image_path):# List where all the descriptors are storeddes_list = []im = cv.imread(image_path, cv.IMREAD_GRAYSCALE)im = cv.resize(im, (300, 300))kpts = sift.detect(im)kpts, des = sift.compute(im, kpts)des_list.append((image_path, des))descriptors = des_list[0][1]for image_path, descriptor in des_list[0:]:descriptors = np.vstack((descriptors, descriptor))test_features = np.zeros((1, k), "float32")words, distance = vq(des_list[0][1], voc)for w in words:test_features[0][w] += 1# Perform Tf-Idf vectorizationnbr_occurences = np.sum((test_features > 0) * 1, axis=0)idf = np.array(np.log((1.0 + 1) / (1.0 * nbr_occurences + 1)), 'float32')# Scale the featurestest_features = stdSlr.transform(test_features)# Perform the predictionspredictions = [classes_names[i] for i in clf.predict(test_features)]return predictions
if __name__ == "__main__":test_path = "dataset/test/"testing_names = os.listdir(test_path)image_paths = []for training_name in testing_names:dir = os.path.join(test_path, training_name)class_path = imutils.imlist(dir)image_paths += class_pathfor image_path in image_paths:predictions = predict_image(image_path)print("image: %s, classes : %s"%(image_path, predictions))

测试集预测运行结果:

"C:\Program Files\Python\Python36\python.exe" D:/python/image_classification/demo.py
image: dataset/test/aeroplane\test_1.jpg, classes : ['aeroplane']
image: dataset/test/aeroplane\test_2.jpg, classes : ['aeroplane']
image: dataset/test/aeroplane\test_3.jpg, classes : ['aeroplane']
image: dataset/test/bicycle\test_1.jpg, classes : ['bicycle']
image: dataset/test/bicycle\test_2.JPG, classes : ['bicycle']
image: dataset/test/bicycle\test_3.jpg, classes : ['bicycle']
image: dataset/test/car\test_1.jpg, classes : ['car']
image: dataset/test/car\test_2.jpg, classes : ['car']
image: dataset/test/car\test_3.jpg, classes : ['car']

总结

只需要几十张图像训练集,就可以对后续的图像做出一个简单的分类预测,对于一些要求不高的web项目来说,植入的成本与代价很小,值得一试!同时为了减小计算量,我对图像的最大尺度resize到300x300大小。

下载1:OpenCV-Contrib扩展模块中文版教程

在「小白学视觉」公众号后台回复:扩展模块中文教程即可下载全网第一份OpenCV扩展模块教程中文版,涵盖扩展模块安装、SFM算法、立体视觉、目标跟踪、生物视觉、超分辨率处理等二十多章内容。

下载2:Python视觉实战项目52讲

在「小白学视觉」公众号后台回复:Python视觉实战项目即可下载包括图像分割、口罩检测、车道线检测、车辆计数、添加眼线、车牌识别、字符识别、情绪检测、文本内容提取、面部识别等31个视觉实战项目,助力快速学校计算机视觉。

下载3:OpenCV实战项目20讲

在「小白学视觉」公众号后台回复:OpenCV实战项目20讲即可下载含有20个基于OpenCV实现20个实战项目,实现OpenCV学习进阶。

交流群

欢迎加入公众号读者群一起和同行交流,目前有SLAM、三维视觉、传感器、自动驾驶、计算摄影、检测、分割、识别、医学影像、GAN、算法竞赛等微信群(以后会逐渐细分),请扫描下面微信号加群,备注:”昵称+学校/公司+研究方向“,例如:”张三 + 上海交大 + 视觉SLAM“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~

使用OpenCV与sklearn实现基于词袋模型的图像分类预测与搜索相关推荐

  1. 文档相似度之词条相似度word2vec、及基于词袋模型计算sklearn实现和gensim

    文档相似度之词条相似度word2vec.及基于词袋模型计算sklearn实现和gensim 示例代码: import jieba import pandas as pd from gensim.mod ...

  2. 基于词袋模型的语言生成模型

    作者:禅与计算机程序设计艺术 机器学习领域 近几年来,随着深度学习.强化学习等一系列新型机器学习技术的出现,人们开始认识到深度学习算法在解决实际任务中的潜力.近些年,无论是深度学习.强化学习还是监督学 ...

  3. 作为SLAM中最常用的闭环检测方法,视觉词袋模型技术详解来了

    摘自:https://mp.weixin.qq.com/s/OZnnuA31tEaVt0vnDOy5hQ 作为SLAM中最常用的闭环检测方法,视觉词袋模型技术详解来了 原创 小翼 飞思实验室 今天 基 ...

  4. 开源!用于3D激光雷达SLAM回环检测的实时词袋模型BoW3D

    点击进入->3D视觉工坊学习交流群 0. 笔者个人体会 回环检测对于SLAM系统的全局一致性有着至关重要的影响.现有的视觉SLAM回环检测大多是基于词袋模型,也就是2012年推出的BoW2库和2 ...

  5. 基于Kaggle数据的词袋模型文本分类教程

     基于Kaggle数据的词袋模型文本分类教程 发表于23小时前| 454次阅读| 来源FastML| 0 条评论| 作者Zygmunt Z 词袋模型文本分类word2vecn-gram机器学习 w ...

  6. R语言构建文本分类模型:文本数据预处理、构建词袋模型(bag of words)、构建xgboost文本分类模型、基于自定义函数构建xgboost文本分类模型

    R语言构建文本分类模型:文本数据预处理.构建词袋模型(bag of words).构建xgboost文本分类模型.基于自定义函数构建xgboost文本分类模型 目录

  7. R语言构建文本分类模型并使用LIME进行模型解释实战:文本数据预处理、构建词袋模型、构建xgboost文本分类模型、基于文本训练数据以及模型构建LIME解释器解释多个测试语料的预测结果并可视化

    R语言构建文本分类模型并使用LIME进行模型解释实战:文本数据预处理.构建词袋模型.构建xgboost文本分类模型.基于文本训练数据以及模型构建LIME解释器解释多个测试语料的预测结果并可视化 目录

  8. 基于视词袋模型的场景识别

    基于视词袋模型的场景识别 一.问题 场景内容的自动识别是计算机视觉领域的一个重要问题,对目标识别.检测基于内容的图像检索等计算机视觉方面的应用具有重要意义,最近12306的图片验证码系统就可以看做一个 ...

  9. 如何设计好词袋模型BoW模型的类类型

    回顾过去自己写过的一些词袋模型,比如BoW图像检索Python实战.图像检索(CBIR)三剑客之BoF.VLAD.FV以及Bag of Words cpp实现,这些写出来的要么只是助于自己理解词袋模型 ...

最新文章

  1. deepin系统引导_国产 Linux 发行版 深度操作系统 20 正式版发布
  2. 彻底解决显示Opencv中Mat图像到Mfc窗口问题
  3. 使用ArcGIS Server发布我们的数据
  4. Angular学习笔记第一节 基本概念
  5. 当网页数据到达用户计算机,当网页数据到达用户计算机时,数据进行转换步骤是()...
  6. u盘版linux initramfs,Linux_内核升级后 出现initramfs错误问题解决, 出现initramfs找不到/root /hos - phpStudy...
  7. HDU2201 熊猫阿波的故事【概率】
  8. 商城系统订单超时自动取消解决方案
  9. 数据可视化API之弧线图实现
  10. CSS动画入门:一分钟实现球体上下跳动动画效果
  11. 外汇EA如何需看这四点
  12. python中eval函数的用法
  13. php getimagesize 导致系统变慢
  14. 从南极之争谈软件架构十个技巧,及成功团队具备的气质
  15. ChatGPT与文心一言对比思考
  16. 最全IDC数据中心知识讲解(一)
  17. java实现Prim算法
  18. SpringMVC_初级总结
  19. 【单片机毕业设计】【mcuclub-jj-003】基于单片机的八层电梯的设计
  20. 安搭Share:小康时代新青年

热门文章

  1. 喜大普奔!GitHub官方文档推出中文版
  2. 百度SLG拿下前锤子科技CTO钱晨,还要合并小鱼在家? | 极客头条
  3. 为了智能驾驶,李彦宏要改造城市道路
  4. AI与区块链的融合会给人类带来什么?
  5. 出门问问李志飞:小米让别人无路可走,我也要让它走起来没有那么方便
  6. AI一分钟 | 贾跃亭这次真的没钱了,法拉第只够发到年底工资;自动驾驶风云:Uber竟被爆料收购窃取Waymo机密的公司
  7. 突然就懵了!面试官问我:线程池中多余的线程是如何回收的?
  8. fastjson 的作者,在阿里内网挨骂了?!
  9. 碰到Maven依赖冲突,想砸电脑?这个IDEA插件必须了解一下...
  10. 如何在微服务架构中实现安全性?