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

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


http://www.kler.cn/a/584997.html

相关文章:

  • FORTRAN语言的数据结构
  • GStreamer —— 2.17、Windows下Qt加载GStreamer库后运行 - “播放教程 5:色彩平衡“(附:完整源码)
  • FastJSON与Java序列化:数据处理与转换的关键技术
  • Python爬虫实战:基于 Scrapy 框架的腾讯视频数据采集研究
  • 『Rust』Rust运行环境搭建
  • Linux笔记之通配符和正则表达式的区别
  • cocos creator 3.8如何在代码中打印drawcall,fps
  • Matlab 灰度质心法提取条纹中心线
  • Git的详细使用方法
  • 基于stm32的视觉物流机器人
  • 智慧城市新基建!图扑智慧路灯,点亮未来城市生活!
  • AWS云编排详解-Cloud Formation
  • 一文讲清楚CUDA与PyTorch、GPU之间的关系
  • Gemini Robotics:Google DeepMind 让 AI 机器人真正“动”起来!
  • 深度学习——Diffusion Model学习,扩散模型
  • 编程助手学Python--Deepseek对OpenAI的Python库调用GPT-4模型生成对话回复理解
  • 解决启动Vue项目时遇到的 error:0308010C:digital envelope routines::unsupported 错误
  • 深入理解pytest框架中的conftest.py:使用与作用原理
  • 爬取数据时如何处理可能出现的异常?
  • 系统开发资源