当前位置: 首页 > news >正文

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

相关文章:

  • Jenkins实现自动化构建与部署:上手攻略
  • 机器学习 Day03 Numpy基本使用
  • 2025 ubuntu24系统宿主机上在线安装mysql数据库完整演示
  • Python连接SQL SEVER数据库全流程
  • 基于大模型的结节性甲状腺肿诊疗全流程预测与方案研究报告
  • 【原理理解】图像SNR信噪比理解
  • 关于JSONArray转换为JSONObject的问题解决
  • 第四章:表单与交互:打造你的「数据捕手」
  • 攻防世界 file_include【php://filter详解】
  • Reactor中的Flux和Mono的区别
  • 【2025】基于PHP+Vue的电影购票系统(源码+文档+调试+图文修改+答疑)
  • 如何用HTML5 Canvas实现电子签名功能✍️
  • 【c语言逻辑运算和判断选取精选题】
  • DeepSeek V3 并行训练、推理优化点(一)
  • Linux losetup循环设备
  • MySQL初阶 | 库的操作
  • 项目-苍穹外卖(二)增加用户+用户分页查询
  • 十三、OSG学习笔记-osgDB文件读写
  • .net 6.0 webapi支持 xml返回xml json返回json
  • Vue.js 与 Axios 实现音乐自由
  • 已婚女子谎称单身恋爱2年多,骗取男友38.8万元彩礼被刑拘
  • 2025年上海市工程建设标准国际化工作要点发布
  • 斗鱼一季度直播收入降近三成,语音社交服务推高广告等收入,称将持续打击涉赌行为
  • 王毅将出席《关于建立国际调解院的公约》签署仪式
  • “集团结婚”:近百年前革新婚俗的尝试
  • 夜驾遇东北虎隔窗对视?延吉林业局:村里有牛被咬死,保险公司会理赔