最近在作圖像匹配的事,發現原來有個叫 OpenCV 的庫,很是強大,跨平臺、多語言接口、在計算機視覺和圖像處理上提供了多個通用算法,應用的領域包括了物體識別、人臉識別、圖像分割、機器視覺、運動分析。由於涉及了一些圖像處理的概念和算法,對於常年作業務系統的程序員來講不多碰這領域,因此分享一下問題的處理過程。html
先看下這個庫的安裝,它是跨平臺的,主流的操做系統都支持,以操做系統 OS X 、開發工具 IntelliJ IDEA 爲例,看下這個庫的安裝和配置過程。java
OpenCV 最新的版本是3.2.0,因此看這個版本的安裝說明,頁面上有Linux、Windows、Android、iOS等不一樣平臺的安裝介紹,因爲我用的是Java,因此直接看 Introduction to Java Development 安裝過程共分下面幾步:git
git clone git://github.com/opencv/opencv.git
複製代碼
cd opencv
git checkout 2.4
複製代碼
mkdir build
cd build
複製代碼
cmake -DBUILD_SHARED_LIBS=OFF ..
複製代碼
當控制檯輸出裏有"To be built"這行,裏面包含了"java",則表示項目編譯成功了。 程序員
make -j8
複製代碼
執行完 make 命令後看下 build 目錄下的 bin 目錄內容,若是有文件叫 opencv-2413.jar,則說明 opencv 已經編譯安裝好了。 github
以上步驟執行完,實際就具有了 java 接口訪問 openCV 的能力了。而要在 IntelliJ IDEA 中訪問 OpenCV ,還須要兩部配置:算法
給項目添加 jar 包 在項目的 Libraries 中添加上面 build 以後的 bin 目錄下的 opencv-2413.jar 數組
寫一個測試 OpenCV 環境的類bash
package org.study.image.openCV;
import org.opencv.core.Core;
public class OpenCVTest {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
}
複製代碼
這個類裏面就一句話,加載本地的openCV庫。app
此時運行這個類會報 UnsatisfiedLinkError 的錯誤,提示【no opencv_java2413 in java.library.path】: 工具
要解決的問題是判斷一張圖片是否在另外一張圖片之中,好比下面這兩張圖:
肉眼上能看出來下面的圖片其實就是在上面圖片的左下區域,但是用計算機如何給出這種判斷來代替人工呢?
最開始搜到的資料就是 OpenCV 裏的模板匹配,其原理是經過一張模板圖片去另外一張圖中找到與模板類似部分(以上面的例子來講模板就是上面的小圖)。模板匹配算法是指經過滑窗的方式在待匹配的圖像上滑動,經過比較模板與子圖的類似度,找到類似度最大的子圖。
所謂滑窗就是經過滑動圖片,使得圖像塊一次移動一個像素(從左到右,從上往下)。在每個位置,都進行一次度量計算來這個圖像塊和原圖像的特定區域的像素值類似程度。當類似度足夠高時,就認爲找到了目標。顯然,這裏「類似程度」的定義依賴於具體的計算公式給出的結果,不一樣算法結果也不同。
目前 OpenCV 裏提供了六種算法:TM_SQDIFF(平方差匹配法)、TM_SQDIFF_NORMED(歸一化平方差匹配法)、TM_CCORR(相關匹配法)、TM_CCORR_NORMED(歸一化相關匹配法)、TM_CCOEFF(相關係數匹配法)、TM_CCOEFF_NORMED(歸一化相關係數匹配法)。
下面是 Java 中使用 OpenCV 的模板匹配的代碼:
package org.study.image.openCV;
import org.opencv.core.*;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
public class OpenCVTest {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat source, template;
//將文件讀入爲OpenCV的Mat格式
source = Highgui.imread("/Users/niwei/Downloads/原圖.jpeg");
template = Highgui.imread("/Users/niwei/Downloads/模板.jpeg");
//建立於原圖相同的大小,儲存匹配度
Mat result = Mat.zeros(source.rows() - template.rows() + 1, source.cols() - template.cols() + 1, CvType.CV_32FC1);
//調用模板匹配方法
Imgproc.matchTemplate(source, template, result, Imgproc.TM_SQDIFF_NORMED);
//規格化
Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1);
//得到最可能點,MinMaxLocResult是其數據格式,包括了最大、最小點的位置x、y
Core.MinMaxLocResult mlr = Core.minMaxLoc(result);
Point matchLoc = mlr.minLoc;
//在原圖上的對應模板可能位置畫一個綠色矩形
Core.rectangle(source, matchLoc, new Point(matchLoc.x + template.width(), matchLoc.y + template.height()), new Scalar(0, 255, 0));
//將結果輸出到對應位置
Highgui.imwrite("/Users/niwei/Downloads/匹配結果.jpeg", source);
}
}
複製代碼
但它的缺陷在於若是模板圖片發生了旋轉、縮放以後,這種經過滑窗的模板匹配方式就會失效,那又如何處理呢?
要解決旋轉縮放後的模板圖片再匹配原圖的問題,就用到了計算機視覺處理算法中的特徵變換匹配算法。其思路是先找到圖像中的一些「穩定點」,這些點不會由於視角的改變、光照的變化、噪音的干擾而消失,好比角點、邊緣點、暗區域的亮點以及亮區域的暗點。這樣若是兩幅圖中有相同的景物,那麼穩定點就會在兩幅圖像的相同景物上同時出現,這樣就能實現匹配。
OpenCV 中針對特徵點匹配問題已經提供了不少算法,包括 FAST 、SIFT 、SURF 、ORB 等,這裏不贅述這些算法之間的區別,直接以 SURF 爲例,看下 OpenCV 裏面如何應用的。
package com.zhiqu.image.recognition;
import org.opencv.calib3d.Calib3d;
import org.opencv.core.*;
import org.opencv.features2d.*;
import org.opencv.highgui.Highgui;
import java.util.LinkedList;
import java.util.List;
/**
* Created by niwei on 2017/4/28.
*/
public class ImageRecognition {
private float nndrRatio = 0.7f;//這裏設置既定值爲0.7,該值可自行調整
private int matchesPointCount = 0;
public float getNndrRatio() {
return nndrRatio;
}
public void setNndrRatio(float nndrRatio) {
this.nndrRatio = nndrRatio;
}
public int getMatchesPointCount() {
return matchesPointCount;
}
public void setMatchesPointCount(int matchesPointCount) {
this.matchesPointCount = matchesPointCount;
}
public void matchImage(Mat templateImage, Mat originalImage) {
MatOfKeyPoint templateKeyPoints = new MatOfKeyPoint();
//指定特徵點算法SURF
FeatureDetector featureDetector = FeatureDetector.create(FeatureDetector.SURF);
//獲取模板圖的特徵點
featureDetector.detect(templateImage, templateKeyPoints);
//提取模板圖的特徵點
MatOfKeyPoint templateDescriptors = new MatOfKeyPoint();
DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.SURF);
System.out.println("提取模板圖的特徵點");
descriptorExtractor.compute(templateImage, templateKeyPoints, templateDescriptors);
//顯示模板圖的特徵點圖片
Mat outputImage = new Mat(templateImage.rows(), templateImage.cols(), Highgui.CV_LOAD_IMAGE_COLOR);
System.out.println("在圖片上顯示提取的特徵點");
Features2d.drawKeypoints(templateImage, templateKeyPoints, outputImage, new Scalar(255, 0, 0), 0);
//獲取原圖的特徵點
MatOfKeyPoint originalKeyPoints = new MatOfKeyPoint();
MatOfKeyPoint originalDescriptors = new MatOfKeyPoint();
featureDetector.detect(originalImage, originalKeyPoints);
System.out.println("提取原圖的特徵點");
descriptorExtractor.compute(originalImage, originalKeyPoints, originalDescriptors);
List<MatOfDMatch> matches = new LinkedList();
DescriptorMatcher descriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
System.out.println("尋找最佳匹配");
/**
* knnMatch方法的做用就是在給定特徵描述集合中尋找最佳匹配
* 使用KNN-matching算法,令K=2,則每一個match獲得兩個最接近的descriptor,而後計算最接近距離和次接近距離之間的比值,當比值大於既定值時,才做爲最終match。
*/
descriptorMatcher.knnMatch(templateDescriptors, originalDescriptors, matches, 2);
System.out.println("計算匹配結果");
LinkedList<DMatch> goodMatchesList = new LinkedList();
//對匹配結果進行篩選,依據distance進行篩選
matches.forEach(match -> {
DMatch[] dmatcharray = match.toArray();
DMatch m1 = dmatcharray[0];
DMatch m2 = dmatcharray[1];
if (m1.distance <= m2.distance * nndrRatio) {
goodMatchesList.addLast(m1);
}
});
matchesPointCount = goodMatchesList.size();
//當匹配後的特徵點大於等於 4 個,則認爲模板圖在原圖中,該值能夠自行調整
if (matchesPointCount >= 4) {
System.out.println("模板圖在原圖匹配成功!");
List<KeyPoint> templateKeyPointList = templateKeyPoints.toList();
List<KeyPoint> originalKeyPointList = originalKeyPoints.toList();
LinkedList<Point> objectPoints = new LinkedList();
LinkedList<Point> scenePoints = new LinkedList();
goodMatchesList.forEach(goodMatch -> {
objectPoints.addLast(templateKeyPointList.get(goodMatch.queryIdx).pt);
scenePoints.addLast(originalKeyPointList.get(goodMatch.trainIdx).pt);
});
MatOfPoint2f objMatOfPoint2f = new MatOfPoint2f();
objMatOfPoint2f.fromList(objectPoints);
MatOfPoint2f scnMatOfPoint2f = new MatOfPoint2f();
scnMatOfPoint2f.fromList(scenePoints);
//使用 findHomography 尋找匹配上的關鍵點的變換
Mat homography = Calib3d.findHomography(objMatOfPoint2f, scnMatOfPoint2f, Calib3d.RANSAC, 3);
/**
* 透視變換(Perspective Transformation)是將圖片投影到一個新的視平面(Viewing Plane),也稱做投影映射(Projective Mapping)。
*/
Mat templateCorners = new Mat(4, 1, CvType.CV_32FC2);
Mat templateTransformResult = new Mat(4, 1, CvType.CV_32FC2);
templateCorners.put(0, 0, new double[]{0, 0});
templateCorners.put(1, 0, new double[]{templateImage.cols(), 0});
templateCorners.put(2, 0, new double[]{templateImage.cols(), templateImage.rows()});
templateCorners.put(3, 0, new double[]{0, templateImage.rows()});
//使用 perspectiveTransform 將模板圖進行透視變以矯正圖象獲得標準圖片
Core.perspectiveTransform(templateCorners, templateTransformResult, homography);
//矩形四個頂點
double[] pointA = templateTransformResult.get(0, 0);
double[] pointB = templateTransformResult.get(1, 0);
double[] pointC = templateTransformResult.get(2, 0);
double[] pointD = templateTransformResult.get(3, 0);
//指定取得數組子集的範圍
int rowStart = (int) pointA[1];
int rowEnd = (int) pointC[1];
int colStart = (int) pointD[0];
int colEnd = (int) pointB[0];
Mat subMat = originalImage.submat(rowStart, rowEnd, colStart, colEnd);
Highgui.imwrite("/Users/niwei/Desktop/opencv/原圖中的匹配圖.jpg", subMat);
//將匹配的圖像用用四條線框出來
Core.line(originalImage, new Point(pointA), new Point(pointB), new Scalar(0, 255, 0), 4);//上 A->B
Core.line(originalImage, new Point(pointB), new Point(pointC), new Scalar(0, 255, 0), 4);//右 B->C
Core.line(originalImage, new Point(pointC), new Point(pointD), new Scalar(0, 255, 0), 4);//下 C->D
Core.line(originalImage, new Point(pointD), new Point(pointA), new Scalar(0, 255, 0), 4);//左 D->A
MatOfDMatch goodMatches = new MatOfDMatch();
goodMatches.fromList(goodMatchesList);
Mat matchOutput = new Mat(originalImage.rows() * 2, originalImage.cols() * 2, Highgui.CV_LOAD_IMAGE_COLOR);
Features2d.drawMatches(templateImage, templateKeyPoints, originalImage, originalKeyPoints, goodMatches, matchOutput, new Scalar(0, 255, 0), new Scalar(255, 0, 0), new MatOfByte(), 2);
Highgui.imwrite("/Users/niwei/Desktop/opencv/特徵點匹配過程.jpg", matchOutput);
Highgui.imwrite("/Users/niwei/Desktop/opencv/模板圖在原圖中的位置.jpg", originalImage);
} else {
System.out.println("模板圖不在原圖中!");
}
Highgui.imwrite("/Users/niwei/Desktop/opencv/模板特徵點.jpg", outputImage);
}
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String templateFilePath = "/Users/niwei/Desktop/opencv/模板.jpeg";
String originalFilePath = "/Users/niwei/Desktop/opencv/原圖.jpeg";
//讀取圖片文件
Mat templateImage = Highgui.imread(templateFilePath, Highgui.CV_LOAD_IMAGE_COLOR);
Mat originalImage = Highgui.imread(originalFilePath, Highgui.CV_LOAD_IMAGE_COLOR);
ImageRecognition imageRecognition = new ImageRecognition();
imageRecognition.matchImage(templateImage, originalImage);
System.out.println("匹配的像素點總數:" + imageRecognition.getMatchesPointCount());
}
}
複製代碼
代碼解釋見文中的註釋,執行結果以下: