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

相关推荐
wwlsm_zql2 小时前
「赤兔」Chitu 框架深度解读(十四):核心算子优化
人工智能·1024程序员节
AKAMAI4 小时前
Fermyon推出全球最快边缘计算平台:WebAssembly先驱携手Akamai云驱动无服务器技术新浪潮
人工智能·云计算·边缘计算
云雾J视界4 小时前
TMS320C6000 VLIW架构并行编程实战:加速AI边缘计算推理性能
人工智能·架构·边缘计算·dsp·vliw·tms320c6000
想ai抽4 小时前
基于AI Agent的数据资产自动化治理实验
人工智能·langchain·embedding
小马过河R5 小时前
AIGC视频生成之Deepseek、百度妙笔组合实战小案例
人工智能·深度学习·计算机视觉·百度·aigc
june-Dai Yi6 小时前
免费的大语言模型API接口
人工智能·语言模型·自然语言处理·chatgpt·api接口
王哈哈^_^6 小时前
【数据集】【YOLO】【目标检测】农作物病害数据集 11498 张,病害检测,YOLOv8农作物病虫害识别系统实战训推教程。
人工智能·深度学习·算法·yolo·目标检测·计算机视觉·1024程序员节
数据库安全6 小时前
牛品推荐|分类分级效能飞跃:美创智能数据安全分类分级平台
大数据·人工智能·分类
却道天凉_好个秋6 小时前
卷积神经网络CNN(六):卷积、归一化与ReLU总结
人工智能·神经网络·cnn
澄澈青空~6 小时前
blender拓扑建模教程
人工智能·blender