Python-OpenCV 处理图像(四):图像直方图和反向投影

来源:互联网 发布:odysseusota4 windows 编辑:程序博客网 时间:2024/05/17 00:13

当我们想比较两张图片相似度的时候,可以使用这一节提到的技术

  • 直方图对比

  • 反向投影

关于这两种技术的原理可以参考我上面贴的链接,下面是示例的代码:

0x01. 绘制直方图

import cv2.cv as cvdef drawGraph(ar,im, size): #Draw the histogram on the image    minV, maxV, minloc, maxloc = cv.MinMaxLoc(ar) #Get the min and max value    hpt = 0.9 * histsize    for i in range(size):        intensity = ar[i] * hpt / maxV #Calculate the intensity to make enter in the image        cv.Line(im, (i,size), (i,int(size-intensity)),cv.Scalar(255,255,255)) #Draw the line        i += 1#---- Gray imageorig = cv.LoadImage("img/lena.jpg", cv.CV_8U)histsize = 256 #Because we are working on grayscale pictures which values within 0-255hist = cv.CreateHist([histsize], cv.CV_HIST_ARRAY, [[0,histsize]], 1)cv.CalcHist([orig], hist) #Calculate histogram for the given grayscale picturehistImg = cv.CreateMat(histsize, histsize, cv.CV_8U) #Image that will contain the graph of the repartition of valuesdrawGraph(hist.bins, histImg, histsize)cv.ShowImage("Original Image", orig)cv.ShowImage("Original Histogram", histImg)#---------------------#---- Equalized imageimEq = cv.CloneImage(orig)cv.EqualizeHist(imEq, imEq) #Equlize the original imagehistEq = cv.CreateHist([histsize], cv.CV_HIST_ARRAY, [[0,histsize]], 1)cv.CalcHist([imEq], histEq) #Calculate histogram for the given grayscale pictureeqImg = cv.CreateMat(histsize, histsize, cv.CV_8U) #Image that will contain the graph of the repartition of valuesdrawGraph(histEq.bins, eqImg, histsize)cv.ShowImage("Image Equalized", imEq)cv.ShowImage("Equalized HIstogram", eqImg)#--------------------------------cv.WaitKey(0)

0x02. 反向投影

import cv2.cv as cvim = cv.LoadImage("img/lena.jpg", cv.CV_8U)cv.SetImageROI(im, (1, 1,30,30))histsize = 256 #Because we are working on grayscale pictureshist = cv.CreateHist([histsize], cv.CV_HIST_ARRAY, [[0,histsize]], 1)cv.CalcHist([im], hist)cv.NormalizeHist(hist,1) # The factor rescale values by multiplying values by the factor_,max_value,_,_ = cv.GetMinMaxHistValue(hist)if max_value == 0:    max_value = 1.0cv.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("Original Image", im)cv.ShowImage("BackProjected", res)cv.WaitKey(0)
0 0