在使用Lire实现图片检索功能比较简单,主要分为两步,第一步创建索引,第二步索引检索

一、创建索引

创建索引主要是使用DocumentBuilderFactory 创建 DocumentBuilder,例如DocumentBuilderFactory.getCEDDDocumentBuilder().
将图片加入索引index 需要以下2步:
    使用 DocumentBuilder 创建Document:builder.createDocument(FileInputStream, String).(第一个参数是图片文件)
    将document 加入 index.

Document就是lucene中的文档,它建立的文档包含了图像的某个特征和图像的标识字符串两个Field。通过调用createDocument就能返回每个图像对应特征和标识的文档,用lucene的IndexWriter就能将它写入索引文件。

LIRE支持很多种的特征值。具体可以看 DocumentBuilderFactory 类的源代码。也可以使用 ChainedDocumentBuilder 同时使用多种特征值。

创建索引的方法如下代码所示

/*** Simple index creation with Lire** @author Mathias Lux, mathias@juggle.at*/
public class Indexer {public static void main(String[] args) throws IOException {// Checking if arg[0] is there and if it is a directory.boolean passed = false;if (args.length > 0) {File f = new File(args[0]);System.out.println("Indexing images in " + args[0]);if (f.exists() && f.isDirectory()) passed = true;}if (!passed) {System.out.println("No directory given as first argument.");System.out.println("Run \"Indexer <directory>\" to index files of a directory.");System.exit(1);}// Getting all images from a directory and its sub directories.ArrayList<String> images = FileUtils.getAllImages(new File(args[0]), true);// Creating a CEDD document builder and indexing al files.DocumentBuilder builder = DocumentBuilderFactory.getCEDDDocumentBuilder();// Creating an Lucene IndexWriterIndexWriterConfig conf = new IndexWriterConfig(LuceneUtils.LUCENE_VERSION,new WhitespaceAnalyzer(LuceneUtils.LUCENE_VERSION));IndexWriter iw = new IndexWriter(FSDirectory.open(new File("index")), conf);// Iterating through images building the low level featuresfor (Iterator<String> it = images.iterator(); it.hasNext(); ) {String imageFilePath = it.next();System.out.println("Indexing " + imageFilePath);try {BufferedImage img = ImageIO.read(new FileInputStream(imageFilePath));Document document = builder.createDocument(img, imageFilePath);iw.addDocument(document);} catch (Exception e) {System.err.println("Error reading image or indexing it.");e.printStackTrace();}}// closing the IndexWriteriw.close();System.out.println("Finished indexing.");}
}

二、索引检索

检索用的接口类ImageSearcherFactory实现检索功能,提供了很多的检索方式,其中常用的createDefaultSearcher。Searcher搜索结果返回的是ImageSearchHits,它就是ArrayList results结果集,根据图片的相似度由高到低的一个集合。

    /** * Simple image retrieval with Lire * @author Mathias Lux, mathias <at> juggle <dot> at */  public class Searcher {  public static void main(String[] args) throws IOException {  // Checking if arg[0] is there and if it is an image.  BufferedImage img = null;  boolean passed = false;  if (args.length > 0) {  File f = new File(args[0]);  if (f.exists()) {  try {  img = ImageIO.read(f);  passed = true;  } catch (IOException e) {  e.printStackTrace();    }  }  }  if (!passed) {  System.out.println("No image given as first argument.");  System.out.println("Run \"Searcher <query image>\" to search for <query image>.");  System.exit(1);  }  IndexReader ir = DirectoryReader.open(FSDirectory.open(new File("index")));  ImageSearcher searcher = ImageSearcherFactory.createCEDDImageSearcher(10);  ImageSearchHits hits = searcher.search(img, ir);  for (int i = 0; i < hits.length(); i++) {  String fileName = hits.doc(i).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];  System.out.println(hits.score(i) + ": \t" + fileName);  }  }  }  

三、使用实例
新建一个web project,工程名为LireDemo,项目结构如图所示;

TestImageSearch.java

package com.lire.demo;import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;import javax.imageio.ImageIO;import net.semanticmetadata.lire.DocumentBuilder;
import net.semanticmetadata.lire.DocumentBuilderFactory;
import net.semanticmetadata.lire.ImageDuplicates;
import net.semanticmetadata.lire.ImageSearchHits;
import net.semanticmetadata.lire.ImageSearcher;
import net.semanticmetadata.lire.ImageSearcherFactory;import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;public class TestImageSearch {private static String INDEX_PATH = "F:\\LireImageSearch\\index";// 索引文件存放路径private static String INDEX_FILE_PATH = "F:\\LireImageSearch\\images"; //要索引的图片文件目录private static String SEARCH_FILE = "F:\\LireImageSearch\\testImg\\1000.jpg";//用于搜索的图片public void createIndex() throws Exception {//创建一个合适的文件生成器,Lire针对图像的多种属性有不同的生成器DocumentBuilder db = DocumentBuilderFactory.getCEDDDocumentBuilder();IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_33, new SimpleAnalyzer(Version.LUCENE_33));IndexWriter iw = new IndexWriter(FSDirectory.open(new File(INDEX_PATH)), iwc);File parent = new File(INDEX_FILE_PATH);for (File f : parent.listFiles()) {// 创建Lucene索引Document doc = db.createDocument(new FileInputStream(f), f.getName());// 将文件加入索引iw.addDocument(doc);}iw.optimize();iw.close();}public void searchSimilar() throws Exception {IndexReader ir = IndexReader.open(FSDirectory.open(new File(INDEX_PATH)));//打开索引ImageSearcher is = ImageSearcherFactory.createDefaultSearcher();//创建一个图片搜索器FileInputStream fis = new FileInputStream(SEARCH_FILE);//搜索图片源BufferedImage bi = ImageIO.read(fis);ImageSearchHits ish = is.search(bi, ir);//根据上面提供的图片搜索相似的图片for (int i = 0; i < 10; i++) {//显示前10条记录(根据匹配度排序)System.out.println(ish.score(i) + ": " + ish.doc(i).getFieldable(DocumentBuilder.FIELD_NAME_IDENTIFIER).stringValue());}}//测试前先将包含重复图片的文件进行索引public void searchDuplicates() throws Exception {IndexReader ir = IndexReader.open(FSDirectory.open(new File(INDEX_PATH)));ImageSearcher is = ImageSearcherFactory.createDefaultSearcher();ImageDuplicates id = is.findDuplicates(ir);//查找重复的图片,如果没有,则返回nullfor (int i = 0; id != null && i < id.length(); i++) {System.out.println(id.getDuplicate(i).toString());}}/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubTestImageSearch ts = new TestImageSearch();try {ts.createIndex();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}try {ts.searchSimilar();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

测试结果



源码下载:http://download.csdn.net/detail/davebobo/9657211

Lire使用实例:创建索引 搜索相似图片相关推荐

  1. lucene全文搜索之三:生成索引字段,创建索引文档(给索引字段加权)基于lucene5.5.3...

    前言:上一章中我们已经实现了索引器的创建,但是我们没有索引文档,本章将会讲解如何生成字段.创建索引文档,给字段加权以及保存文档到索引器目录 luncene5.5.3集合jar包下载地址:http:// ...

  2. c mysql创建索引,如何创建mysql索引

    索引是一种特殊的文件(innodb数据表上的索引是表空间的一个组成部分),它们包含着对数据表里所有记录的引用指针. 注: [1]索引不是万能的! 索引可以加快数据检索操作,但会使数据修改操作变慢.每修 ...

  3. mysql 创建索引失败_mysql创建多列索引及优化 - 没有所谓的失败!除非你不再尝试! - PHPChina ......

    什么是索引? 索引用来快速地寻找那些具有特定值的记录,所有MySQL索引都以B-树的形式保存.如果没有索引,执行查询时MySQL必须从第一个记录开始扫描整个表的所有记录,直至找到符合要求的记录.表里面 ...

  4. 创建表的时候创建索引

    创建索引是指在某个表的一列或多列上建立一个索引,以便提高对表的访问速度.创建索引有3种方式,这3种方式分别是创建表的时候创建索引.在已经存在的表上创建索引和使用ALTER TABLE语句来创建索引.本 ...

  5. LIRE的使用:创建索引

    LIRE(Lucene Image REtrieval)提供一种的简单方式来创建基于图像特性的Lucene索引.利用该索引就能够构建一个基于内容的图像检索(content- based image r ...

  6. 利用Lucene.net搭建站内搜索(3)---创建索引

    Lucene.net提供了很全面的数据搜索操作,你可以利用Lucene.net检索磁盘中的文件,网页,数据库中的数据,但是前提是预先对数据创建索引. Lucene索引过程分为三个主要的操作阶段:将数据 ...

  7. Lucene+Tika 文件索引的创建与搜索

    2019独角兽企业重金招聘Python工程师标准>>> 使用Lucene+Tika进行文件索引的创建与查询,在Windows环境下测试没问题,可以解析各种文件(Tika支持的),另外 ...

  8. OpenCV FLANN在数据集中搜索查询图片的实例(附完整代码)

    OpenCV FLANN在数据集中搜索查询图片的实例 OpenCV FLANN在数据集中搜索查询图片的实例 OpenCV FLANN在数据集中搜索查询图片的实例 #include <iostre ...

  9. Elasticsearch:使用最新的 Python client 8.0 来创建索引并搜索

    随着 Elastic Stack 8.0 的推出,Elastic 也推出了最新的 python client 8.0 安装包.这是 Elasticsearch 的官方低级 Python 客户端. 它的 ...

最新文章

  1. 快速入门linux系统的iptables防火墙 1 本机与外界的基本通信管理
  2. 使用指针判断数组是否为上三角矩阵
  3. JavaScript常见集合操作
  4. linux网络编程常用函数详解与实例(socket--bind--listen--accept)
  5. MySQL双主(主主)架构方案
  6. 存储过程mysql报错1271_mysqldump备份失败以及解决方法汇总
  7. jQuery 项目 兼容IE ,缓存问题,等总结
  8. 冲刺One之站立会议3 /2015-5-16
  9. 守护进程-----杀死自己的进程再重新启动自己
  10. 帆软决策报表JS实现点击超链切换TAB页
  11. 主子式大于等于零的矩阵是半正定矩阵的证明方法之一
  12. Matlab2017a汉化版软件详细安装教程
  13. OpenWRT LEDE固件安装
  14. 用计算机教学体育,体育教学中计算机的应用
  15. C语言数组比较相等memcmp,使用memcmp比较两个变量结果一定吗?
  16. php ppt如何转换成pdf,ppt转pdf格式转换器 PPT批量转换成PDF 怎样把PPT格式转换成PDF格式...
  17. 2019年安徽大学ACM/ICPC实验室新生赛
  18. 打开终端如何自动进入conda环境
  19. 知识科普:5G是什么
  20. 什么?这个岗位薪资秒杀一众程序员?

热门文章

  1. Oracle ASH分析详解
  2. Cookies 的读写
  3. (AFDEN)2022 SIGIR 面向情感分析的方面级特征提取与增强网络
  4. 如何让IE8默认启动InPrivate浏览模式
  5. 带你实现开发者头条APP(四)---首页优化(加入design包)
  6. 最新自动搞蚂蚁森林任务工具
  7. 乐视市值是360两倍说明啥:卖水模式终结 生态战开打
  8. 首页上的热门商品和最新商品
  9. 单片机中OTA升级流程及bootload软件框架
  10. MatConvNet配置详解,吐血整理Win10+MATLAB2019a+VS2015+cuda11.0