Python-OpenCV 处理图像(四):图像直方图和反向投影
生活随笔
收集整理的這篇文章主要介紹了
Python-OpenCV 处理图像(四):图像直方图和反向投影
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
當(dāng)我們想比較兩張圖片相似度的時(shí)候,可以使用這一節(jié)提到的技術(shù)
-
直方圖對(duì)比
-
反向投影
關(guān)于這兩種技術(shù)的原理可以參考我上面貼的鏈接,下面是示例的代碼:
0x01. 繪制直方圖
import cv2.cv as cvdef drawGraph(ar,im, size): #Draw the histogram on the imageminV, maxV, minloc, maxloc = cv.MinMaxLoc(ar) #Get the min and max valuehpt = 0.9 * histsizefor i in range(size):intensity = ar[i] * hpt / maxV #Calculate the intensity to make enter in the imagecv.Line(im, (i,size), (i,int(size-intensity)),cv.Scalar(255,255,255)) #Draw the linei += 1#---- Gray image orig = 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 values drawGraph(hist.bins, histImg, histsize)cv.ShowImage("Original Image", orig) cv.ShowImage("Original Histogram", histImg) #---------------------#---- Equalized image imEq = 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 picture eqImg = cv.CreateMat(histsize, histsize, cv.CV_8U) #Image that will contain the graph of the repartition of values drawGraph(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 pictures hist = 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.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("Original Image", im) cv.ShowImage("BackProjected", res) cv.WaitKey(0)總結(jié)
以上是生活随笔為你收集整理的Python-OpenCV 处理图像(四):图像直方图和反向投影的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python-OpenCV 处理图像(三
- 下一篇: Python-OpenCV 处理图像(五