OpenCV实现图像搜索引擎

OpenCV实现图像搜索引擎

简单介绍一下OpenCV

OpenCV was designed for computational efficiency and with a strong focus on real-time applications. Written in optimized C/C++, the library can take advantage of multi-core processing. Enabled with OpenCL, it can take advantage of the hardware acceleration of the underlying heterogeneous compute platform. Adopted all around the world, OpenCV has more than 47 thousand people of user community and estimated number of downloads exceeding 9 million. Usage ranges from interactive art, to mines inspection, stitching maps on the web or through advanced robotics.

OpenCV(Open Source Computer Vision Library)的计算效率很高且能够完成实时任务。OpenCV库由优化的C/C++代码编写而成,能够充分发挥多核处理和硬件加速的优势。OpenCV有大量技术社区和超过900万的下载量,它的使用范围极为广泛,如人机互动、资源检查、拼接地图等。

0.Python+OpenCV实现图像搜索引擎

之前看到谷歌和百度出了图像搜索引擎,查阅了相关资料深入了解了图像搜索引擎的算法原理。一部分参考了用Python和OpenCV创建一个图片搜索引擎的完整指南。决定自己实现一个简单的图像搜索引擎,也可以让自己更快地查找mac中的图片。为什么使用OpenCV+Python实现图像搜索引擎呢?

  • 首先,OpenCV是一个开源的计算机视觉处理库,在计算机视觉图像处理模式识别中有广泛的应用。接口安全易用,而且跨平台做的相当不错,是一个不可多得的计算机图像及视觉处理库。

  • 其次,Python的语法更加易用,贴近自然语言,极为灵活。虽然计算效率并不高,但快速开发上它远胜于C++或其他语言,引入pysco能够优化python代码中的循环,一定程度上缩小与C/C++在计算上的差距。而且图像处理中需要大量的矩阵计算,引入numpy做矩阵运算能够降低编程的冗杂度,更多地把精力放在匹配的逻辑上,而非计算的细枝末节。

1. 图像搜索原理

图像搜索算法基本可以分为如下步骤:

  • 提取图像特征。如采用SIFT、指纹算法函数、哈希函数、bundling features算法等。当然如知乎中所言,也可以针对特定的图像集群采用特定的模式设计算法,从而提高匹配的精度。如已知所有图像的中间部分在颜色空间或构图上有显著的区别,就可以加强对中间部分的分析,从而更加高效地提取图像特征。

  • 图像特征的存储。一般将图像特征量化为数据存放于索引表中,并存储在外部存储介质中,搜索图片时仅搜索索引表中的图像特征,按匹配程度从高到低查找类似图像。对于图像尺寸分辩率不同的情况可以采用降低采样或归一化方法

  • 相似度匹配。如存储的是特征向量,则比较特征向量之间的加权后的平方距离。如存储的是散列码,则比较Hamming距离。初筛后,还可以进一步筛选最佳图像集。

2. 图片搜索引擎算法及框架设计

基本步骤

  • 采用颜色空间特征提取器和构图空间特征提取器提取图像特征
  • 图像索引表构建驱动程序生成待搜索图像库的图像特征索引表
  • 图像搜索引擎驱动程序执行搜索命令,生成原图图像特征并传入图片搜索匹配器。
  • 图片搜索匹配内核执行搜索匹配任务。返回前limit个最佳匹配图像。

所需模块

  • numpy。科学计算和矩阵运算利器。
  • cv2。OpenCV的python模块接入。
  • re。正则化模块。解析csv中的图像构图特征和色彩特征集。
  • csv。高效地读入csv文件。
  • glob。正则获取文件夹中文件路径。
  • argparse。设置命令行参数。

封装类及驱动程序

  • 颜色空间特征提取器ColorDescriptor。
  1. 类成员bins记录HSV色彩空间生成的色相、饱和度及明度分布直方图的最佳bins分配。bins分配过多则可能导致程序效率低下,匹配难度和匹配要求过分苛严;bins分配过少则会导致匹配精度不足,不能表证图像特征。
  2. 成员函数getHistogram(self, image, mask, isCenter)。生成图像的色彩特征分布直方图。image为待处理图像,mask为图像处理区域的掩模,isCenter判断是否为图像中心,从而有效地对色彩特征向量做加权处理。权重weight5.0。采用OpenCV的calcHist()方法获得直方图,normalize()方法归一化。
  3. 成员函数describe(self, image)。将图像从BGR色彩空间转为HSV色彩空间(此处应注意OpenCV读入图像的色彩空间为BGR而非RGB)。生成左上、右上、左下、右下、中心部分的掩模。中心部分掩模的形状为椭圆形。这样能够有效区分中心部分和边缘部分,从而在getHistogram()方法中对不同部位的色彩特征做加权处理
1
class ColorDescriptor:
2
    __slot__ = ["bins"]
3
    def __init__(self, bins):
4
        self.bins = bins
5
    def getHistogram(self, image, mask, isCenter):
6
        # get histogram
7
        imageHistogram = cv2.calcHist([image], [0, 1, 2], mask, self.bins, [0, 180, 0, 256, 0, 256])
8
        # normalize
9
        imageHistogram = cv2.normalize(imageHistogram, imageHistogram).flatten()
10
        if isCenter:
11
            weight = 5.0
12
            for index in xrange(len(imageHistogram)):
13
                imageHistogram[index] *= weight
14
        return imageHistogram
15
    def describe(self, image):
16
        image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
17
        features = []
18
        # get dimension and center
19
        height, width = image.shape[0], image.shape[1]
20
        centerX, centerY = int(width * 0.5), int(height * 0.5)
21
        # initialize mask dimension
22
        segments = [(0, centerX, 0, centerY), (0, centerX, centerY, height), (centerX, width, 0, centerY), (centerX, width, centerY, height)]
23
        # initialize center part
24
        axesX, axesY = int(width * 0.75) / 2, int (height * 0.75) / 2
25
        ellipseMask = numpy.zeros([height, width], dtype="uint8")
26
        cv2.ellipse(ellipseMask, (centerX, centerY), (axesX, axesY), 0, 0, 360, 255, -1)
27
        # initialize corner part
28
        for startX, endX, startY, endY in segments:
29
            cornerMask = numpy.zeros([height, width], dtype="uint8")
30
            cv2.rectangle(cornerMask, (startX, startY), (endX, endY), 255, -1)
31
            cornerMask = cv2.subtract(cornerMask, ellipseMask)
32
            # get histogram of corner part
33
            imageHistogram = self.getHistogram(image, cornerMask, False)
34
            features.append(imageHistogram)
35
        # get histogram of center part
36
        imageHistogram = self.getHistogram(image, ellipseMask, True)
37
        features.append(imageHistogram)
38
        # return
39
        return features
  • 构图空间特征提取器StructureDescriptor。
  1. 类成员dimension。将所有图片归一化(降低采样)为dimension所规定的尺寸。由此才能够用于统一的匹配和构图空间特征的生成。
  2. 成员函数describe(self, image)。将图像从BGR色彩空间转为HSV色彩空间(此处应注意OpenCV读入图像的色彩空间为BGR而非RGB)。返回HSV色彩空间的矩阵,等待在搜索引擎核心中的下一步处理。
1
class StructureDescriptor:
2
    __slot__ = ["dimension"]
3
    def __init__(self, dimension):
4
        self.dimension = dimension
5
    def describe(self, image):
6
        image = cv2.resize(image, self.dimension, interpolation=cv2.INTER_CUBIC)
7
        # image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
8
        return image
  • 图片搜索匹配内核Searcher。
  1. 类成员colorIndexPathstructureIndexPath。记录色彩空间特征索引表路径和结构特征索引表路径。
  2. 成员函数solveColorDistance(self, features, queryFeatures, eps = 1e-5)。求featuresqueryFeatures特征向量的二范数eps是为了避免除零错误
  3. 成员函数solveStructureDistance(self, structures, queryStructures, eps = 1e-5)。同样是求特征向量的二范数eps是为了避免除零错误。需作统一化处理,color和structure特征向量距离相对比例适中,不可过分偏颇。
  4. 成员函数searchByColor(self, queryFeatures)。使用csv模块的reader方法读入索引表数据。采用re的split方法解析数据格式。用字典searchResults存储query图像与库中图像的距离,键为图库内图像名imageName,值为距离distance
  5. 成员函数transformRawQuery(self, rawQueryStructures)。将未处理的query图像矩阵转为用于匹配的特征向量形式
  6. 成员函数searchByStructure(self, rawQueryStructures)。类似4。
  7. 成员函数search(self, queryFeatures, rawQueryStructures, limit = 3)。将searchByColor方法和searchByStructure的结果汇总,获得总匹配分值,分值越低代表综合距离越小,匹配程度越高。返回前limit个最佳匹配图像。
1
class Searcher:
2
    __slot__ = ["colorIndexPath", "structureIndexPath"]
3
    def __init__(self, colorIndexPath, structureIndexPath):
4
        self.colorIndexPath, self.structureIndexPath = colorIndexPath, structureIndexPath
5
    def solveColorDistance(self, features, queryFeatures, eps = 1e-5):
6
        distance = 0.5 * numpy.sum([((a - b) ** 2) / (a + b + eps) for a, b in zip(features, queryFeatures)])
7
        return distance
8
    def solveStructureDistance(self, structures, queryStructures, eps = 1e-5):
9
        distance = 0
10
        normalizeRatio = 5e3
11
        for index in xrange(len(queryStructures)):
12
            for subIndex in xrange(len(queryStructures[index])):
13
                a = structures[index][subIndex]
14
                b = queryStructures[index][subIndex]
15
                distance += (a - b) ** 2 / (a + b + eps)
16
        return distance / normalizeRatio
17
    def searchByColor(self, queryFeatures):
18
        searchResults = {}
19
        with open(self.colorIndexPath) as indexFile:
20
            reader = csv.reader(indexFile)
21
            for line in reader:
22
                features = []
23
                for feature in line[1:]:
24
                    feature = feature.replace("[", "").replace("]", "")
25
                    findStartPosition = 0
26
                    feature = re.split("\s+", feature)
27
                    rmlist = []
28
                    for index, strValue in enumerate(feature):
29
                        if strValue == "":
30
                            rmlist.append(index)
31
                    for _ in xrange(len(rmlist)):
32
                        currentIndex = rmlist[-1]
33
                        rmlist.pop()
34
                        del feature[currentIndex]
35
                    feature = [float(eachValue) for eachValue in feature]
36
                    features.append(feature)
37
                distance = self.solveColorDistance(features, queryFeatures)
38
                searchResults[line[0]] = distance
39
            indexFile.close()
40
        # print "feature", sorted(searchResults.iteritems(), key = lambda item: item[1], reverse = False)
41
        return searchResults
42
    def transformRawQuery(self, rawQueryStructures):
43
        queryStructures = []
44
        for substructure in rawQueryStructures:
45
            structure = []
46
            for line in substructure:
47
                for tripleColor in line:
48
                    structure.append(float(tripleColor))
49
            queryStructures.append(structure)
50
        return queryStructures
51
    def searchByStructure(self, rawQueryStructures):
52
        searchResults = {}
53
        queryStructures = self.transformRawQuery(rawQueryStructures)
54
        with open(self.structureIndexPath) as indexFile:
55
            reader = csv.reader(indexFile)
56
            for line in reader:
57
                structures = []
58
                for structure in line[1:]:
59
                    structure = structure.replace("[", "").replace("]", "")
60
                    structure = re.split("\s+", structure)
61
                    if structure[0] == "":
62
                        structure = structure[1:]
63
                    structure = [float(eachValue) for eachValue in structure]
64
                    structures.append(structure)
65
                distance = self.solveStructureDistance(structures, queryStructures)
66
                searchResults[line[0]] = distance
67
            indexFile.close()
68
        # print "structure", sorted(searchResults.iteritems(), key = lambda item: item[1], reverse = False)
69
        return searchResults
70
    def search(self, queryFeatures, rawQueryStructures, limit = 3):
71
        featureResults = self.searchByColor(queryFeatures)
72
        structureResults = self.searchByStructure(rawQueryStructures)
73
        results = {}
74
        for key, value in featureResults.iteritems():
75
            results[key] = value + structureResults[key]
76
        results = sorted(results.iteritems(), key = lambda item: item[1], reverse = False)
77
        return results[ : limit]
  • 图像索引表构建驱动index.py。

  • 引入color_descriptorstructure_descriptor。用于解析图片库图像,获得色彩空间特征向量和构图空间特征向量。

  • argparse设置命令行参数。参数包括图片库路径、色彩空间特征索引表路径、构图空间特征索引表路径。

  • glob获得图片库路径。

  • 生成索引表文本并写入csv文件。

  • 可采用如下命令行形式启动驱动程序。

1
python index.py --dataset dataset --colorindex color——index.csv --structure structure_index.csv

dataset为图片库路径。color_index.csv为色彩空间特征索引表路径。structure_index.csv为构图空间特征索引表路径。

1
import color_descriptor
2
import structure_descriptor
3
import glob
4
import argparse
5
import cv2
6
7
searchArgParser = argparse.ArgumentParser()
8
searchArgParser.add_argument("-d", "--dataset", required = True, help = "Path to the directory that contains the images to be indexed")
9
searchArgParser.add_argument("-c", "--colorindex", required = True, help = "Path to where the computed color index will be stored")
10
searchArgParser.add_argument("-s", "--structureindex", required = True, help = "Path to where the computed structure index will be stored")
11
arguments = vars(searchArgParser.parse_args())
12
13
idealBins = (8, 12, 3)
14
colorDesriptor = color_descriptor.ColorDescriptor(idealBins)
15
16
output = open(arguments["colorindex"], "w")
17
18
for imagePath in glob.glob(arguments["dataset"] + "/*.jpg"):
19
    imageName = imagePath[imagePath.rfind("/") + 1 : ]
20
    image = cv2.imread(imagePath)
21
    features = colorDesriptor.describe(image)
22
    # write features to file
23
    features = [str(feature).replace("\n", "") for feature in features]
24
    output.write("%s,%s\n" % (imageName, ",".join(features)))
25
# close index file
26
output.close()
27
28
idealDimension = (16, 16)
29
structureDescriptor = structure_descriptor.StructureDescriptor(idealDimension)
30
31
output = open(arguments["structureindex"], "w")
32
33
for imagePath in glob.glob("dataset" + "/*.jpg"):
34
    imageName = imagePath[imagePath.rfind("/") + 1 : ]
35
    image = cv2.imread(imagePath)
36
    structures = structureDescriptor.describe(image)
37
    # write structures to file
38
    structures = [str(structure).replace("\n", "") for structure in structures]
39
    output.write("%s,%s\n" % (imageName, ",".join(structures)))
40
# close index file
41
output.close()
  • 图像搜索引擎驱动searchEngine.py。

  • 引入color_descriptorstructure_descriptor。用于解析待匹配(搜索)的图像,获得色彩空间特征向量和构图空间特征向量。

  • argparse设置命令行参数。参数包括图片库路径、色彩空间特征索引表路径、构图空间特征索引表路径、待搜索图片路径。

  • 生成索引表文本并写入csv文件。

  • 可采用如下命令行形式启动驱动程序。

1
python searchEngine.py -c color_index.csv -s structure_index.csv -r dataset -q query/pyramid.jpg

dataset为图片库路径。color_index.csv为色彩空间特征索引表路径。structure_index.csv为构图空间特征索引表路径,query/pyramid.jpg为待搜索图片路径。

1
searchArgParser = argparse.ArgumentParser()
2
searchArgParser.add_argument("-c", "--colorindex", required = True, help = "Path to where the computed color index will be stored")
3
searchArgParser.add_argument("-s", "--structureindex", required = True, help = "Path to where the computed structure index will be stored")
4
searchArgParser.add_argument("-q", "--query", required = True, help = "Path to the query image")
5
searchArgParser.add_argument("-r", "--resultpath", required = True, help = "Path to the result path")
6
searchArguments = vars(searchArgParser.parse_args())
7
8
idealBins = (8, 12, 3)
9
idealDimension = (16, 16)
10
11
colorDescriptor = color_descriptor.ColorDescriptor(idealBins)
12
structureDescriptor = structure_descriptor.StructureDescriptor(idealDimension)
13
queryImage = cv2.imread(searchArguments["query"])
14
colorIndexPath = searchArguments["colorindex"]
15
structureIndexPath = searchArguments["structureindex"]
16
resultPath = searchArguments["resultpath"]
17
18
queryFeatures = colorDescriptor.describe(queryImage)
19
queryStructures = structureDescriptor.describe(queryImage)
20
21
imageSearcher = searcher.Searcher(colorIndexPath, structureIndexPath)
22
searchResults = imageSearcher.search(queryFeatures, queryStructures)
23
24
for imageName, score in searchResults:
25
    queryResult = cv2.imread(resultPath + "/" + imageName)
26
    cv2.imshow("Result Score: " + str(int(score)) + " (lower is better)", queryResult)
27
    cv2.waitKey(0)
28
29
cv2.imshow("Query", queryImage)
30
cv2.waitKey(0)

3. 搜索引擎测试

Qeury: fish.jpg

Result(匹配分值越低越好):

  1. Score: 0
  2. Score: 17
  3. Score: 21

Qeury: forest.jpg

Result(匹配分值越低越好):

  1. Score: 0
  2. Score: 33
  3. Score: 33

Qeury: trip.jpg

Result(匹配分值越低越好):

  1. Score: 0
  2. Score: 23
  3. Score: 24

Qeury: zebra.jpg

Result(匹配分值越低越好):

  1. Score: 0
  2. Score: 23
  3. Score: 25

总结:总能搜索到完全一致的图像(即原图)。搜索得到的图像与原图基本符合。测试成功。

4. Python源代码

color_descriptor.py

1
import cv2
2
import numpy
3
4
class ColorDescriptor:
5
    __slot__ = ["bins"]
6
    def __init__(self, bins):
7
        self.bins = bins
8
    def getHistogram(self, image, mask, isCenter):
9
        # get histogram
10
        imageHistogram = cv2.calcHist([image], [0, 1, 2], mask, self.bins, [0, 180, 0, 256, 0, 256])
11
        # normalize
12
        imageHistogram = cv2.normalize(imageHistogram, imageHistogram).flatten()
13
        if isCenter:
14
            weight = 5.0
15
            for index in xrange(len(imageHistogram)):
16
                imageHistogram[index] *= weight
17
        return imageHistogram
18
    def describe(self, image):
19
        image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
20
        features = []
21
        # get dimension and center
22
        height, width = image.shape[0], image.shape[1]
23
        centerX, centerY = int(width * 0.5), int(height * 0.5)
24
        # initialize mask dimension
25
        segments = [(0, centerX, 0, centerY), (0, centerX, centerY, height), (centerX, width, 0, centerY), (centerX, width, centerY, height)]
26
        # initialize center part
27
        axesX, axesY = int(width * 0.75) / 2, int (height * 0.75) / 2
28
        ellipseMask = numpy.zeros([height, width], dtype="uint8")
29
        cv2.ellipse(ellipseMask, (centerX, centerY), (axesX, axesY), 0, 0, 360, 255, -1)
30
        # initialize corner part
31
        for startX, endX, startY, endY in segments:
32
            cornerMask = numpy.zeros([height, width], dtype="uint8")
33
            cv2.rectangle(cornerMask, (startX, startY), (endX, endY), 255, -1)
34
            cornerMask = cv2.subtract(cornerMask, ellipseMask)
35
            # get histogram of corner part
36
            imageHistogram = self.getHistogram(image, cornerMask, False)
37
            features.append(imageHistogram)
38
        # get histogram of center part
39
        imageHistogram = self.getHistogram(image, ellipseMask, True)
40
        features.append(imageHistogram)
41
        # return
42
        return features

structure_descriptor.py

1
import cv2
2
3
class StructureDescriptor:
4
    __slot__ = ["dimension"]
5
    def __init__(self, dimension):
6
        self.dimension = dimension
7
    def describe(self, image):
8
        image = cv2.resize(image, self.dimension, interpolation=cv2.INTER_CUBIC)
9
        # image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
10
        return image

searcher.py

1
import numpy
2
import csv
3
import re
4
5
class Searcher:
6
    __slot__ = ["colorIndexPath", "structureIndexPath"]
7
    def __init__(self, colorIndexPath, structureIndexPath):
8
        self.colorIndexPath, self.structureIndexPath = colorIndexPath, structureIndexPath
9
    def solveColorDistance(self, features, queryFeatures, eps = 1e-5):
10
        distance = 0.5 * numpy.sum([((a - b) ** 2) / (a + b + eps) for a, b in zip(features, queryFeatures)])
11
        return distance
12
    def solveStructureDistance(self, structures, queryStructures, eps = 1e-5):
13
        distance = 0
14
        normalizeRatio = 5e3
15
        for index in xrange(len(queryStructures)):
16
            for subIndex in xrange(len(queryStructures[index])):
17
                a = structures[index][subIndex]
18
                b = queryStructures[index][subIndex]
19
                distance += (a - b) ** 2 / (a + b + eps)
20
        return distance / normalizeRatio
21
    def searchByColor(self, queryFeatures):
22
        searchResults = {}
23
        with open(self.colorIndexPath) as indexFile:
24
            reader = csv.reader(indexFile)
25
            for line in reader:
26
                features = []
27
                for feature in line[1:]:
28
                    feature = feature.replace("[", "").replace("]", "")
29
                    findStartPosition = 0
30
                    feature = re.split("\s+", feature)
31
                    rmlist = []
32
                    for index, strValue in enumerate(feature):
33
                        if strValue == "":
34
                            rmlist.append(index)
35
                    for _ in xrange(len(rmlist)):
36
                        currentIndex = rmlist[-1]
37
                        rmlist.pop()
38
                        del feature[currentIndex]
39
                    feature = [float(eachValue) for eachValue in feature]
40
                    features.append(feature)
41
                distance = self.solveColorDistance(features, queryFeatures)
42
                searchResults[line[0]] = distance
43
            indexFile.close()
44
        # print "feature", sorted(searchResults.iteritems(), key = lambda item: item[1], reverse = False)
45
        return searchResults
46
    def transformRawQuery(self, rawQueryStructures):
47
        queryStructures = []
48
        for substructure in rawQueryStructures:
49
            structure = []
50
            for line in substructure:
51
                for tripleColor in line:
52
                    structure.append(float(tripleColor))
53
            queryStructures.append(structure)
54
        return queryStructures
55
    def searchByStructure(self, rawQueryStructures):
56
        searchResults = {}
57
        queryStructures = self.transformRawQuery(rawQueryStructures)
58
        with open(self.structureIndexPath) as indexFile:
59
            reader = csv.reader(indexFile)
60
            for line in reader:
61
                structures = []
62
                for structure in line[1:]:
63
                    structure = structure.replace("[", "").replace("]", "")
64
                    structure = re.split("\s+", structure)
65
                    if structure[0] == "":
66
                        structure = structure[1:]
67
                    structure = [float(eachValue) for eachValue in structure]
68
                    structures.append(structure)
69
                distance = self.solveStructureDistance(structures, queryStructures)
70
                searchResults[line[0]] = distance
71
            indexFile.close()
72
        # print "structure", sorted(searchResults.iteritems(), key = lambda item: item[1], reverse = False)
73
        return searchResults
74
    def search(self, queryFeatures, rawQueryStructures, limit = 3):
75
        featureResults = self.searchByColor(queryFeatures)
76
        structureResults = self.searchByStructure(rawQueryStructures)
77
        results = {}
78
        for key, value in featureResults.iteritems():
79
            results[key] = value + structureResults[key]
80
        results = sorted(results.iteritems(), key = lambda item: item[1], reverse = False)
81
        return results[ : limit]

index.py

1
import color_descriptor
2
import structure_descriptor
3
import glob
4
import argparse
5
import cv2
6
7
searchArgParser = argparse.ArgumentParser()
8
searchArgParser.add_argument("-d", "--dataset", required = True, help = "Path to the directory that contains the images to be indexed")
9
searchArgParser.add_argument("-c", "--colorindex", required = True, help = "Path to where the computed color index will be stored")
10
searchArgParser.add_argument("-s", "--structureindex", required = True, help = "Path to where the computed structure index will be stored")
11
arguments = vars(searchArgParser.parse_args())
12
13
idealBins = (8, 12, 3)
14
colorDesriptor = color_descriptor.ColorDescriptor(idealBins)
15
16
output = open(arguments["colorindex"], "w")
17
18
for imagePath in glob.glob(arguments["dataset"] + "/*.jpg"):
19
    imageName = imagePath[imagePath.rfind("/") + 1 : ]
20
    image = cv2.imread(imagePath)
21
    features = colorDesriptor.describe(image)
22
    # write features to file
23
    features = [str(feature).replace("\n", "") for feature in features]
24
    output.write("%s,%s\n" % (imageName, ",".join(features)))
25
# close index file
26
output.close()
27
28
idealDimension = (16, 16)
29
structureDescriptor = structure_descriptor.StructureDescriptor(idealDimension)
30
31
output = open(arguments["structureindex"], "w")
32
33
for imagePath in glob.glob("dataset" + "/*.jpg"):
34
    imageName = imagePath[imagePath.rfind("/") + 1 : ]
35
    image = cv2.imread(imagePath)
36
    structures = structureDescriptor.describe(image)
37
    # write structures to file
38
    structures = [str(structure).replace("\n", "") for structure in structures]
39
    output.write("%s,%s\n" % (imageName, ",".join(structures)))
40
# close index file
41
output.close()

searchEngine.py

1
import color_descriptor
2
import structure_descriptor
3
import searcher
4
import argparse
5
import cv2
6
7
searchArgParser = argparse.ArgumentParser()
8
searchArgParser.add_argument("-c", "--colorindex", required = True, help = "Path to where the computed color index will be stored")
9
searchArgParser.add_argument("-s", "--structureindex", required = True, help = "Path to where the computed structure index will be stored")
10
searchArgParser.add_argument("-q", "--query", required = True, help = "Path to the query image")
11
searchArgParser.add_argument("-r", "--resultpath", required = True, help = "Path to the result path")
12
searchArguments = vars(searchArgParser.parse_args())
13
14
idealBins = (8, 12, 3)
15
idealDimension = (16, 16)
16
17
colorDescriptor = color_descriptor.ColorDescriptor(idealBins)
18
structureDescriptor = structure_descriptor.StructureDescriptor(idealDimension)
19
queryImage = cv2.imread(searchArguments["query"])
20
colorIndexPath = searchArguments["colorindex"]
21
structureIndexPath = searchArguments["structureindex"]
22
resultPath = searchArguments["resultpath"]
23
24
queryFeatures = colorDescriptor.describe(queryImage)
25
queryStructures = structureDescriptor.describe(queryImage)
26
27
imageSearcher = searcher.Searcher(colorIndexPath, structureIndexPath)
28
searchResults = imageSearcher.search(queryFeatures, queryStructures)
29
30
for imageName, score in searchResults:
31
    queryResult = cv2.imread(resultPath + "/" + imageName)
32
    cv2.imshow("Result Score: " + str(int(score)) + " (lower is better)", queryResult)
33
    cv2.waitKey(0)
34
35
cv2.imshow("Query", queryImage)
36
cv2.waitKey(0)

searchEngineTest.py

1
import cv2
2
import glob
3
import csv
4
import re
5
import numpy
6
import structure_descriptor
7
8
idealDimension = (16, 16)
9
structureDescriptor = structure_descriptor.StructureDescriptor(idealDimension)
10
11
testImage = cv2.imread("query/forest.jpg")
12
rawQueryStructures = structureDescriptor.describe(testImage)
13
14
# index
15
output = open("structureIndex.csv", "w")
16
17
for imagePath in glob.glob("dataset" + "/*.jpg"):
18
    imageName = imagePath[imagePath.rfind("/") + 1 : ]
19
    image = cv2.imread(imagePath)
20
    structures = structureDescriptor.describe(image)
21
    # write structures to file
22
    structures = [str(structure).replace("\n", "") for structure in structures]
23
    output.write("%s,%s\n" % (imageName, ",".join(structures)))
24
# close index file
25
output.close()
26
27
# searcher
28
29
def solveStructureDistance(self, structures, queryStructures, eps = 1e-5):
30
    distance = 0
31
    for index in xrange(len(queryFeatures)):
32
        for subIndex in xrange(len(queryFeatures[index])):
33
            a = features[index][subIndex]
34
            b = queryFeatures[index][subIndex]
35
            distance += (a - b) ** 2 / (a + b + eps)
36
    return distance / 5e3
37
38
queryStructures = []
39
for substructure in rawQueryStructures:
40
    structure = []
41
    for line in substructure:
42
        for tripleColor in line:
43
            structure.append(float(tripleColor))
44
    queryStructures.append(structure)
45
searchResults = {}
46
with open("structureIndex.csv") as indexFile:
47
    reader = csv.reader(indexFile)
48
    for line in reader:
49
        structures = []
50
        for structure in line[1:]:
51
            structure = structure.replace("[", "").replace("]", "")
52
            structure = re.split("\s+", structure)
53
            if structure[0] == "":
54
                structure = structure[1:]
55
            structure = [float(eachValue) for eachValue in structure]
56
            print len(structure)
57
            structures.append(structure)
58
        distance = solveDistance(structures, queryStructures)
59
        searchResults[line[0]] = distance
60
    indexFile.close()
61
searchResults = sorted(searchResults.iteritems(), key=lambda item: item[1], reverse=False)
62
63
print searchResults
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×