Python OpenCV处理图像之图像直方图和反向投影
本文实例为大家分享了PythonOpenCV图像直方图和反向投影的具体代码,供大家参考,具体内容如下
当我们想比较两张图片相似度的时候,可以使用这一节提到的技术
直方图对比
反向投影
关于这两种技术的原理可以参考我上面贴的链接,下面是示例的代码:
0x01.绘制直方图
importcv2.cvascv defdrawGraph(ar,im,size):#Drawthehistogramontheimage minV,maxV,minloc,maxloc=cv.MinMaxLoc(ar)#Gettheminandmaxvalue hpt=0.9*histsize foriinrange(size): intensity=ar[i]*hpt/maxV#Calculatetheintensitytomakeenterintheimage cv.Line(im,(i,size),(i,int(size-intensity)),cv.Scalar(255,255,255))#Drawtheline i+=1 #----Grayimage orig=cv.LoadImage("img/lena.jpg",cv.CV_8U) histsize=256#Becauseweareworkingongrayscalepictureswhichvalueswithin0-255 hist=cv.CreateHist([histsize],cv.CV_HIST_ARRAY,[[0,histsize]],1) cv.CalcHist([orig],hist)#Calculatehistogramforthegivengrayscalepicture histImg=cv.CreateMat(histsize,histsize,cv.CV_8U)#Imagethatwillcontainthegraphoftherepartitionofvalues drawGraph(hist.bins,histImg,histsize) cv.ShowImage("OriginalImage",orig) cv.ShowImage("OriginalHistogram",histImg) #--------------------- #----Equalizedimage imEq=cv.CloneImage(orig) cv.EqualizeHist(imEq,imEq)#Equlizetheoriginalimage histEq=cv.CreateHist([histsize],cv.CV_HIST_ARRAY,[[0,histsize]],1) cv.CalcHist([imEq],histEq)#Calculatehistogramforthegivengrayscalepicture eqImg=cv.CreateMat(histsize,histsize,cv.CV_8U)#Imagethatwillcontainthegraphoftherepartitionofvalues drawGraph(histEq.bins,eqImg,histsize) cv.ShowImage("ImageEqualized",imEq) cv.ShowImage("EqualizedHIstogram",eqImg) #-------------------------------- cv.WaitKey(0)
0x02.反向投影
importcv2.cvascv im=cv.LoadImage("img/lena.jpg",cv.CV_8U) cv.SetImageROI(im,(1,1,30,30)) histsize=256#Becauseweareworkingongrayscalepictures hist=cv.CreateHist([histsize],cv.CV_HIST_ARRAY,[[0,histsize]],1) cv.CalcHist([im],hist) cv.NormalizeHist(hist,1)#Thefactorrescalevaluesbymultiplyingvaluesbythefactor _,max_value,_,_=cv.GetMinMaxHistValue(hist) ifmax_value==0: max_value=1.0 cv.NormalizeHist(hist,256/max_value) cv.ResetImageROI(im) res=cv.CreateMat(im.height,im.width,cv.CV_8U) cv.CalcBackProject([im],res,hist) cv.Rectangle(im,(1,1),(30,30),(0,0,255),2,cv.CV_FILLED) cv.ShowImage("OriginalImage",im) cv.ShowImage("BackProjected",res) cv.WaitKey(0)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。