OpenCV——两幅相同与不同尺寸图像融合

相同尺寸图像融合:

#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <opencv2/imgproc/imgproc.hpp>   
#include <iostream>   
using namespace cv;  
using namespace std;  

int main()  
{  
    //【0】定义相关变量   
    Mat ac, ahand;  
    //【1】读取原始图像并检查图像是否读取成功    
    ac = imread("D:\\OutPutResult\\ImageTest\\ac.jpg");  
    ahand = imread("D:\\OutPutResult\\ImageTest\\ahand.jpg");  
    if (ahand.empty() && ac.empty())        //检验两幅图像是否同时存在  
    {  
    cout << "读取图像有误,请重新输入正确路径!\n";  
    return -1;  
    }  
    //【3】显示原始图像  
    namedWindow("图像1ac");   //创建窗口  
    imshow("图像1ac", ac);    //显示窗口  
    namedWindow("图像2ahand");  
    imshow("图像2ahand", ahand);  
    //【4】调整ahand的大小与ac的大小一致,融合函数addWeighted()要求输入的两个图形尺寸必须相同    
    resize(ahand, ahand, Size(ac.cols, ac.rows));  
    //【5】利用addWeighted()函数对两幅图像进行融合  
    addWeighted(ac, 0.6, ahand, 0.4, 0., ac); //最后融合效果显示在ac图像上  
    /* 
    若不想毁坏原始ac图像,也可建立一个与ac图像类型尺寸一样的新图像,将融合后的图像保存到上面。 
    建立方法: 
    Mat newImage(ac.size(), ac.type()); //newImage与ac类型尺寸相同 
    */  
    namedWindow("图像1与图像2融合效果图");  
    imshow("图像1与图像2融合效果图", ac);  
    //【6】保持等待状态   
    waitKey();  
    return 0;  
}  

结果:



不同尺寸图像融合:

#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <opencv2/imgproc/imgproc.hpp>   
#include <iostream>   
using namespace cv;  
using namespace std;  

int main()  
{  
    //【0】定义相关变量   
    Mat ac, ahand;  
    //【1】读取原始图像并检查图像是否读取成功    
    ac = imread("D:\\OutPutResult\\ImageTest\\ac.jpg");  
    ahand = imread("D:\\OutPutResult\\ImageTest\\ahand.jpg");  
    if (ahand.empty() && ac.empty())        //检验两幅图像是否同时存在  
    {  
    cout << "读取图像有误,请重新输入正确路径!\n";  
    return -1;  
    }  
    //【3】显示原始图像  
    namedWindow("图像1ac");   //创建窗口  
    imshow("图像1ac", ac);    //显示窗口  
    namedWindow("图像2ahand");  
    imshow("图像2ahand", ahand);  
    //【4】利用ROI,获取将要理图像的矩形大小  
    Mat imageROI;  
    imageROI = ac(Rect(20, 40, ahand.cols, ahand.rows));//在ac图像左上角(20,40)处(即起点位置),获取同ahand图像尺寸一致的区域  
    //【5】利用addWeighted()函数对两幅图像进行融合  
    addWeighted(ahand, 0.6, imageROI, 0.4, 0., imageROI);   
    namedWindow("图像1与图像2融合效果图");  
    imshow("图像1与图像2融合效果图", ac);  
    //【6】保持等待状态   
    waitKey();  
    return 0;  
} 

结果:


### 使用OpenCV实现图像拼接 为了使用OpenCV实现图像拼接,主要涉及几个关键步骤:特征点检测、描述符提取、特征匹配以及透视变换。下面是一个详细的Python代码示例来展示这一过程。 #### 准备工作 确保安装了必要的库: ```bash pip install opencv-python-headless numpy ``` #### 加载并预处理图像 首先需要加载待拼接的两幅或多幅图像,并确认它们能够正常读入: ```python import cv2 import numpy as np def load_images(image_paths): images = [] for path in image_paths: img = cv2.imread(path) if img is None or img.size == 0: raise ValueError(f"无法加载图片 {path}") images.append(img) return images ``` #### 特征点检测描述子计算 利用SIFT或其他合适的算法来进行特征点检测和描述子计算: ```python def detect_and_compute_features(images, detector=cv2.SIFT_create()): keypoints_list = [] descriptors_list = [] for img in images: gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) keypoints, descriptors = detector.detectAndCompute(gray_img, None) keypoints_list.append(keypoints) descriptors_list.append(descriptors) return keypoints_list, descriptors_list ``` #### 进行特征匹配 采用FLANN或BFMatcher等方式完成特征之间的匹配操作: ```python def match_features(descriptors1, descriptors2, matcher_type='flann'): good_matches = [] if matcher_type.lower() == 'bf': bf_matcher = cv2.BFMatcher() matches = bf_matcher.knnMatch(descriptors1, descriptors2, k=2) for m, n in matches: if m.distance < 0.7 * n.distance: good_matches.append(m) elif matcher_type.lower() == 'flann': index_params = dict(algorithm=1, trees=5) search_params = dict(checks=50) flann_matcher = cv2.FlannBasedMatcher(index_params, search_params) matches = flann_matcher.knnMatch(descriptors1, descriptors2, k=2) for i, (m, n) in enumerate(matches): if m.distance < 0.7 * n.distance: good_matches.append(m) return good_matches ``` #### 计算单应矩阵并执行透视变换 基于足够的良好匹配点对,可以估计出源图到目标图间的转换关系——即单应矩阵H;接着应用此矩阵实施最终的图像融合: ```python def compute_homography_matrix(src_pts, dst_pts): H, mask = cv2.findHomography(np.float32([pt.pt for pt in src_pts]), np.float32([pt.pt for pt in dst_pts]), method=cv2.RANSAC, ransacReprojThreshold=5.0) return H, mask def warp_perspective_with_padding(img_src, H, dsize=(800, 600)): h, w = img_src.shape[:2] corners = np.array([[0, 0], [w-1, 0], [w-1, h-1], [0, h-1]], dtype=np.float32).reshape(-1, 1, 2) transformed_corners = cv2.perspectiveTransform(corners, H) min_x = int(min(transformed_corners[:, :, 0].min(), 0)) max_x = int(max(transformed_corners[:, :, 0].max(), dsize[0])) min_y = int(min(transformed_corners[:, :, 1].min(), 0)) max_y = int(max(transformed_corners[:, :, 1].max(), dsize[1])) translation_mat = np.eye(3) translation_mat[0][2] = -min_x translation_mat[1][2] = -min_y new_H = np.dot(translation_mat, H) result_size = (max_x-min_x, max_y-min_y) warped_image = cv2.warpPerspective(img_src, new_H, result_size) return warped_image ``` #### 完整流程整合 最后将上述各个部分组合起来形成完整的图像拼接程序框架: ```python if __name__ == "__main__": try: # Step 1: Load Images paths = ["image1.jpg", "image2.jpg"] imgs = load_images(paths)[^1] # Step 2: Detect and Compute Features kp_list, des_list = detect_and_compute_features(imgs) # Step 3: Match Features Between Two Consecutive Images matched_points = match_features(des_list[0], des_list[1]) # Extract Keypoints Correspondences Based On Matches Found Above pts1 = [kp_list[0][match.queryIdx] for match in matched_points] pts2 = [kp_list[1][match.trainIdx] for match in matched_points] # Step 4: Estimate Homography Matrix And Apply Perspective Transformation With Padding homograpy_mtx, _ = compute_homography_matrix(pts1, pts2) stitched_img = warp_perspective_with_padding(imgs[1], homograpy_mtx, imgs[0].shape[::-1][:2]) # Save Or Display The Resultant Panorama Image Here... except Exception as e: print(e) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值