一、圖像分割核心方法
1、閾值分割
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {Mat img = imread("input.jpg", IMREAD_GRAYSCALE);Mat binary;threshold(img, binary, 127, 255, THRESH_BINARY); // 固定閾值分割imwrite("binary.jpg", binary);return 0;
}
優化?:使用adaptiveThreshold
處理光照不均圖像?。
2、分水嶺算法
// 預處理:形態學去噪+距離變換
Mat markers, foreground;
morphologyEx(img, img, MORPH_OPEN, getStructuringElement(MORPH_ELLIPSE, Size(5,5)));
distanceTransform(img, foreground, DIST_L2, 5);
threshold(foreground, markers, 0.7*maxVal, 255, THRESH_BINARY);
markers.convertTo(markers, CV_8U);
// 執行分水嶺分割
watershed(img, markers);
應用場景?:細胞計數、礦石分析?。
二、圖像無縫合并
1、Stitcher類全自動拼接
OpenCV≥4.5.0支持完整Stitcher功能?。
?
#include <opencv2/stitching.hpp>
int main() {vector<Mat> imgs = {imread("img1.jpg"), imread("img2.jpg")};Ptr<Stitcher> stitcher = Stitcher::create(Stitcher::PANORAMA);Mat panorama;Stitcher::Status status = stitcher->stitch(imgs, panorama);if (status == Stitcher::OK) imwrite("result.jpg", panorama);return 0;
}
?參數調優?:
設置setRegistrationResol(0.6)降低分辨率提升速度?。
啟用setExposureCompensator補償光照差異?。
2、手動特征匹配拼接
拼接的基本流程分為以下幾個步驟:
1)圖像讀取:讀取需要拼接的圖像。
2)特征點檢測:在每張圖像中檢測出關鍵點(特征點)。
3)特征點匹配:在不同圖像之間匹配這些特征點。
4)計算變換矩陣:根據匹配的特征點計算圖像之間的變換矩陣。
5)圖像融合:將圖像按照變換矩陣進行拼接,并進行融合處理以消除拼接痕跡。
// 特征檢測與匹配
Ptr<SIFT> sift = SIFT::create();
vector<KeyPoint> kp1, kp2;
Mat des1, des2;
sift->detectAndCompute(img1, noArray(), kp1, des1);
sift->detectAndCompute(img2, noArray(), kp2, des2);FlannBasedMatcher matcher;
vector<DMatch> matches;
matcher.match(des1, des2, matches);// 單應性矩陣計算
vector<Point2f> src_pts, dst_pts;
for(auto m : matches) {src_pts.push_back(kp1[m.queryIdx].pt);dst_pts.push_back(kp2[m.trainIdx].pt);
}
Mat H = findHomography(src_pts, dst_pts, RANSAC, 3);// 圖像變形與融合
warpPerspective(img1, warped, H, Size(img1.cols+img2.cols, img1.rows));
Mat blended;
addWeighted(warped(Rect(0,0,img2.cols,img2.rows)), 0.5, img2, 0.5, 0, blended);
?性能優化?:
用ORB替代SIFT提升3倍速度?。
設置RANSACReprojThreshold=4.0增強魯棒性?。