python 以图搜图百度_基于opencv的图片检索(模仿百度的以图搜图功能)
曾经有一篇文章简单的介绍了CBIR(Content-Based Image Retrieval),详细内容猛戳基于内容的图像检索技(CBIR)术相术介绍。CBIR由于其应用的广泛性,特别是近年来,随着数码设备的迅猛普及,网络上的图片每天以几十亿级的速度猛增,而且对于一些摄影爱好者和自拍族来说,电脑和存储设备里更是有数不清的图片,如何从这么多图片中找到自己所需的图片是困惑很多人的难题。而CBIR正是这问题的一种一种很好的解决方式。
本文将介绍用Python和OpenCV创建一个简单的图片搜索引擎。
系统架构:
CBIR系统的构建主要包括:
1)定义图像描述符(图像特征提取)
这一阶段,需要决定描述图像的哪一方面。图像的可描述特征很多、包括颜色、形状、纹理、能量等,而颜色有分为很多种,如颜色直方图、颜色矩等。在这一阶段,我们选定要提取的颜色特征,根据应用的不同,选取的颜色特征可以是一种或多种。
2)索引化数据集(存储)
现在有了图像描述符,接着就是将这个图像描述符应用得到数据集中的每幅图像,提取这些图像的特征,将其存储起来(如CSV文件、RDBMS、Redis数据库中),这样后续步骤就能使用以便比较。
3)定义相似矩阵
很好,现在有了许多特征向量。但如何比较这些特征向量呢?比较常用的流行的相似性度量方式有:欧几里德距离、余弦距离、或卡方距离、巴氏距离、闵式距离、相关性等。但实际中取决于两点:①、数据集;②、提取的特征类型。
4)检索
上面步骤都完成了,剩下的就是根据输入的图片,从图像库中检索相似的图像并返回了。用户会向系统提交一幅需要搜索的图片(例如从上传窗口或通过移动App提交),而你的任务是:1、提取这幅图像的特征;2、使用相似度函数将这幅图像的特征与已经索引化的特征进行比较。这样,只需根据相似度函数的结果,返回相关的图像就可以了。
环境说明:
python3.6
opencv3
执行说明:
1、首先生成index检索文件:python index.py -d d:/picture/test/ -i d:/picture/index.csv
2、接着就是搜索相似图片:python Search.py -i d:/picture/index.csv -q d:/picture/test/1.jpg -r d:/picture/test/
数据集如下:
展示的结果:
下面是代码部分:
ColorDescriptor.py
importnumpy as npimportcv2classColorDescriptor:def __init__(self, bins):#store the number of bins for the HSV histogram
self.bins =binsdefdescribe(self, image):#convert the image into HSV color space
image =cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
features=[]#grab the dimensions and compute the center of the image
(h,w) = image.shape[:2]
(cx,cy)= (int(w*0.5), int(h*0.5))#segment the image
segments =[(0,cx,0,cy),(cx,w,0,cy),(cx,w,cy,h),(0,cx,cy,h)]#construct an elliptical mask representing the center of the image
(axesX, axesY) =(int(w*0.75)/2, int(h*0.75)/2)
ellipMask= np.zeros(image.shape[:2],dtype="unit8")
cv2.ellipse(ellipMask,(cx,cy),(axesX,axesY),0,0,360,255,-1)#loop over the segments
for(startX,endX, startY, endY) insegments:
cornerMask= np.zeros(image.shpae[:2],dtype="unit8")
cv2.rectangle(cornerMask,(startX,startY),(endX,endY),255,-1)
cornerMask=cv2.subtract(cornerMask, ellipMask)#compute the histogram
hist =self.histogram(image, cornerMask)
features.extend(hist)#compute the ellipse histogram
hist =self.histogram(image, ellipMask)
features.extend(hist)#return the feature vectr
returnfeatures#define the function of histogram
defhistogram(self, image, mask):#extract the color histogram from the masked region
hist = cv2.calcHist([image],[0,1,2],mask, self.bins,[0,180,0,256,0,256])
hist=cv2.normalize(hist).flatten()returnhist
index.py:
"CBIR(Content-Base Image Retrieval)--Extract Features and Indexing"
importColorDescriptorimportargparseimportglobimportcv2
ap=argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="Path to the directory that cntains the images to be indexed")
ap.add_argument("-i", "--index", required=True, help="Path to where the computed index will be stored")
args=vars(ap.parse_args())
cd= ColorDescriptor.ColorDescriptor((8,12,3))#Open the output index file for writing
output = open(args["index"],"w")#use glob to grab the image paths and loop over them
for imagePath in glob.glob(args["dataset"]+"/*.jpg"):#extract the image ID from the image
imageID = imagePath[imagePath.rfind("\\")+1:]
image=cv2.imread(imagePath)#describe the image
features =cd.describe(image)#write feature to file
features = [str(f) for f infeatures]
output.write("%s,%s\n" %(imageID,",".join(features)))#close index file
output.close()
Searcher.py:
"CBIR(Content-Base Image Retrieval)--Similarity and Search"
importnumpy as np#use for processing index.csv
importcsvclassSearcher:def __init__(self, indexPath):
self.indexPath=indexPathdef chi2_distance(self, histA, histB, eps=1e-10):#compute the chi-squred distance
d = 0.5*np.sum([((a-b)**2)/(a+b+eps) for(a,b) inzip(histA,histB)])returnddef search(self, queryFeatures, limit=10):
results={}#open the index file for reading
with open(self.indexPath) as f:#initialize the CSV reader
reader =csv.reader(f)#loop over the rows in the index
for row inreader:#parse out the imageID and features,
#then compute the chi-squared distance
features = [float(x) for x in row[1:]]
d=self.chi2_distance(features, queryFeatures)
results[row[0]]=d
f.close()
results= sorted([(v,k) for (k,v) inresults.items()])returnresults[:limit]#def chi2_distance(self, histA, histB, eps=1e-10):
## compute the chi-squred distance
#d = 0.5*np.sum([((a-b)**2)/(a+b+eps) for(a,b) in zip(histA,histB)])
#return d
Search.py:
"CBIR(Content-Base Image Retrieval)--Search"
importargparseimportcv2importColorDescriptorimportSearcher
ap=argparse.ArgumentParser()
ap.add_argument("-i", "--index", required=True, help="Path to where the computed index will be stored")
ap.add_argument("-q", "--query", required=True, help="Path to query image")
ap.add_argument("-r", "--result_path", required = True, help="Path to the result Path")
args=vars(ap.parse_args())
cd= ColorDescriptor.ColorDescriptor((8,12,3))#load the query image and describe it
query = cv2.imread(args["query"])
features=cd.describe(query)#perform the search
searcher = Searcher.Searcher(args["index"])
results=searcher.search(features)#display the query
cv2.imshow("Query", query)#loop over the results
for(score, resultID) inresults:#load the result image and display it
print(args["index"]+"/"+resultID)
result= cv2.imread(args["result_path"]+"/"+resultID)
cv2.imshow("Result",result)
cv2.waitKey(0)
参考文章:http://python.jobbole.com/80860/
python 以图搜图百度_基于opencv的图片检索(模仿百度的以图搜图功能)相关推荐
- python运动目标检测与跟踪_基于OpenCV的运动目标检测与跟踪
尹俊超,刘直芳:基于 OpenCV 的运动目标检测与跟踪 2011, V ol.32, No.8 2817 0 引 言 运动目标检测跟踪技术在航空航天遥感. 生物医学. 工业 自动化生产. 军事公安目 ...
- python怎么换背景颜色_用opencv给图片换背景色的示例代码
图像平滑 模糊/平滑图片来消除图片噪声 OpenCV函数:cv2.blur(), cv2.GaussianBlur(), cv2.medianBlur(), cv2.bilateralFilter() ...
- python利用opencv去除图片logo_python 基于opencv去除图片阴影
一.前言 如果你自己打印过东西,应该有过这种经历.如果用自己拍的图片,在手机上看感觉还是清晰可见,但是一打印出来就是漆黑一片.比如下面这两张图片: 因为左边的图片有大片阴影,所以打印出来的图片不堪入目 ...
- 基于opencv的图片模板匹配及其简单应用
opencv的图片模板匹配及其简单应用 我的个人博客 基础知识 基于opencv的图片模板匹配 注: python及其相关包的安装不在讨论范围内 opencv提供了图片模板匹配的方法, cv2.mat ...
- cv2 inrange灰度图_基于openCV,PIL的深色多背景复杂验证码图像转灰度二值化,并去噪降噪处理分析...
title: [python]基于openCV,PIL的深色多背景复杂验证码图像转灰度二值化,并去噪降噪处理分析 type: categories copyright: true categories ...
- python实现流媒体传输_基于OpenCV的网络实时视频流传输的实现
很多小伙伴都不会在家里或者办公室安装网络摄像头或监视摄像头.但是有时,大家又希望能够随时随地观看视频直播. 大多数人会选择使用IP摄像机(Internet协议摄像机)而不是CCTV(闭路电视),因为它 ...
- opencv python考勤_基于opencv和dlib人脸识别的员工考勤系统
已打包生成可执行文件exe,可直接下载运行,exe文件及代码均已上传到我的github,点击传送门,打包的具体过程及教程可见pyinstaller简明教程 WorkAttendanceSystem 一 ...
- python读取视频流做人脸识别_基于OpenCV和Keras实现人脸识别系列——二、使用OpenCV通过摄像头捕获实时视频并探测人脸、准备人脸数据...
基于OpenCV和Keras实现人脸识别系列手记: 项目完整代码参见Github仓库. 本篇是上面这一系列手记的第二篇. 在Opencv初接触,图片的基本操作这篇手记中,我介绍了一些图片的基本操作,而 ...
- opencv 边缘平滑_基于OpenCV的车道检测实现(一)
无人驾驶的话题日趋起热,而车道线检测对于无人驾驶的路径规划来讲特别重要.要遵守交通规则,首先的要求便是对车道线检测,而且通过检测车道线可以进一步的检测地面指示标志.进行前碰撞预警策略设计等. 早早就对 ...
- opencv 轮廓放大_基于openCV,PIL的深色多背景复杂验证码图像转灰度二值化,并去噪降噪处理分析...
title: [python]基于openCV,PIL的深色多背景复杂验证码图像转灰度二值化,并去噪降噪处理分析 type: categories copyright: true categories ...
最新文章
- day16-小数据池
- vue3绑定多个事件
- python访问数据库
- 【 Grey Hack 】万金油脚本:常见端口获取Password
- 多个小int的乘法小心溢出哦(记洛谷P1615题WA的经历,Java语言描述)
- Linux统计文件夹下文件数量
- c++ 协程_深入理解异步I/O+epoll+协程
- C语言中强制转换问题
- Numerical Computing with MaTLAB(matlab数值计算)书中的工具箱 ncm下载以及课本答案和程序下载
- AD 画板知识 mil和mm换算(硬件每日一题)
- 期权定价 - BS模型 - 维纳过程和伊藤引理
- 01 - 树莓派简介以及烧录系统
- 移动网络通信技术【移动电话网络介绍】
- 【报错】VMware Workstation 与 Device/Credential Guard 不兼容.在禁用 Device/Credenti
- 100条人生哲理语句
- 小米怎么快速回到顶部_拆解报告:小米小爱鼠标采用炬芯ATB110X蓝牙物联网方案 -...
- java 目录遍历漏洞_路径遍历 漏洞修复
- 保研之路——哈深计算机预推免
- 怎么实现微信公众号生成专属二维码推广来源统计
- java switch finally_java switch语句详解