OpenCV实现图像分割与无缝合并

一、图像分割核心方法

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增强鲁棒性‌。

相关推荐
拾忆-eleven36 分钟前
NLP学习路线图(十四):词袋模型(Bag of Words)
人工智能·学习·自然语言处理·nlp
sbc-study1 小时前
精英-探索双群协同优化(Elite-Exploration Dual Swarm Cooperative Optimization, EEDSCO)
人工智能
白熊1881 小时前
【机器学习基础】机器学习入门核心算法:XGBoost 和 LightGBM
人工智能·算法·机器学习
微学AI3 小时前
智能穿戴新标杆:SD NAND (贴片式SD卡)与 SOC 如何定义 AI 眼镜未来技术路径
人工智能·ai·sd
拾忆-eleven3 小时前
NLP学习路线图(十五):TF-IDF(词频-逆文档频率)
人工智能·学习·自然语言处理·nlp
封奚泽优3 小时前
使用Python绘制节日祝福——以端午节和儿童节为例
人工智能·python·深度学习
全域智图3 小时前
元胞自动机(Cellular Automata, CA)
人工智能·算法·机器学习
富唯智能3 小时前
复合机器人:纠偏算法如何重塑工业精度与效率?
人工智能·工业机器人·智能机器人
s153353 小时前
3.RV1126-OPENCV 图像叠加
人工智能·opencv·计算机视觉
珂朵莉MM3 小时前
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论