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

相关推荐
做人不要太理性几秒前
CANN Runtime 运行时与维测组件:异构任务调度、显存池管理与全链路异常诊断机制解析
人工智能·自动化
算法备案代理3 分钟前
大模型备案与算法备案,企业该如何选择?
人工智能·算法·大模型·算法备案
酷酷的崽7983 分钟前
CANN 生态可维护性与可观测性:构建生产级边缘 AI 系统的运维体系
运维·人工智能
哈__4 分钟前
CANN加速Inpainting图像修复:掩码处理与边缘融合优化
人工智能
深鱼~6 分钟前
ops-transformer算子库:解锁昇腾大模型加速的关键
人工智能·深度学习·transformer·cann
笔画人生10 分钟前
进阶解读:`ops-transformer` 内部实现与性能调优实战
人工智能·深度学习·transformer
池央18 分钟前
CANN oam-tools 诊断体系深度解析:自动化信息采集、AI Core 异常解析与 CI/CD 流水线集成策略
人工智能·ci/cd·自动化
CV@CV22 分钟前
2026自动驾驶商业化提速——从智驾平权到Robotaxi规模化落地
人工智能·机器学习·自动驾驶
财经三剑客23 分钟前
AI元年,春节出行安全有了更好的答案
大数据·人工智能·安全
艾莉丝努力练剑31 分钟前
图像处理全栈加速:ops-cv算子库在CV领域的应用
图像处理·人工智能