2401_87716693 2026-01-24 12:36 采纳率: 0%
浏览 4

拼接图片边界线过于明显


import pyrealsense2 as rs
import numpy as np
import cv2

class DepthCameraProcessor:
    def __init__(self):
        """初始化深度相机处理器"""
        self.config_camera()
        self.setup_parameters()
        
    def config_camera(self):
        """配置相机参数"""
        self.pipeline = rs.pipeline()
        self.config = rs.config()
        
        # 相机流配置
        self.CAMERA_WIDTH = 640
        self.CAMERA_HEIGHT = 480
        self.DEPTH_STREAM = rs.stream.depth
        self.COLOR_STREAM = rs.stream.color
        self.FORMAT_DEPTH = rs.format.z16
        self.FORMAT_COLOR = rs.format.bgr8
        self.FPS = 30
        
        # 分块参数
        self.NUM_BLOCKS = 10
        
        # 显示参数
        self.WINDOW_COMBINED = 'Binary Blocks Combined'
        self.WINDOW_COLOR = 'Color Image'
        self.EXIT_KEY = ord('q')
        
        # 配置流
        self.config.enable_stream(
            self.DEPTH_STREAM, self.CAMERA_WIDTH, self.CAMERA_HEIGHT, 
            self.FORMAT_DEPTH, self.FPS
        )
        self.config.enable_stream(
            self.COLOR_STREAM, self.CAMERA_WIDTH, self.CAMERA_HEIGHT, 
            self.FORMAT_COLOR, self.FPS
        )
        
    def setup_parameters(self):
        """设置运行时参数"""
        self.profile = None
        self.align = None
        self.running = False
        
    def initialize_camera(self):
        """初始化相机并开始采集"""
        try:
            self.profile = self.pipeline.start(self.config)
            self.align = rs.align(self.COLOR_STREAM)
            self.running = True
            print("相机初始化成功")
            return True
        except Exception as e:
            print(f"相机初始化失败: {e}")
            return False
            
    def stop_camera(self):
        """停止相机"""
        if self.running:
            self.pipeline.stop()
            self.running = False
            print("相机已停止")
            
    def get_frames(self):
        """获取对齐的帧数据"""
        try:
            frames = self.pipeline.wait_for_frames(timeout_ms=5000)
            aligned_frames = self.align.process(frames)
            
            depth_frame = aligned_frames.get_depth_frame()
            color_frame = aligned_frames.get_color_frame()
            
            if not depth_frame or not color_frame:
                return None, None, None
                
            depth_image = np.asanyarray(depth_frame.get_data())
            color_image = np.asanyarray(color_frame.get_data())
            height, width = depth_image.shape[:2]
            
            return depth_image, color_image, (height, width)
            
        except Exception as e:
            print(f"获取帧数据失败: {e}")
            return None, None, None
            
    @staticmethod
    def split_depth_into_blocks(depth_image, num_blocks):
        """将深度图分割成指定数量的块"""
        h, w = depth_image.shape[:2]
        base_block_height = h // num_blocks
        remainder = h % num_blocks
        
        blocks = []
        current_y = 0
        
        for i in range(num_blocks):
            current_block_height = base_block_height + 1 if i < remainder else base_block_height
            start_y = current_y
            end_y = current_y + current_block_height
            current_y = end_y
            
            block = depth_image[start_y:end_y, :]
            blocks.append(block)
            
        return blocks, (h, w)
        
    @staticmethod
    def normalize_depth_blocks(blocks):
        """对深度块进行归一化处理"""
        normalized_blocks = []
        
        for i, block in enumerate(blocks):
            valid_data = block.copy()
            valid_mask = valid_data > 0
            
            if np.any(valid_mask):
                min_val = np.min(valid_data[valid_mask])
                max_val = np.max(valid_data[valid_mask])
                
                # 归一化到 [0, 1]
                normalized_float = (valid_data - min_val) / (max_val - min_val)
                normalized_float = np.clip(normalized_float, 0, 1)
                
                # 转换为 uint8
                normalized_uint8 = (normalized_float * 255).astype(np.uint8)
                normalized_uint8[~valid_mask] = 0
            else:
                min_val = max_val = 0
                normalized_uint8 = np.zeros_like(block, dtype=np.uint8)
                
            normalized_blocks.append(normalized_uint8)
            
            # 打印信息
            info = f"{min_val:.0f}-{max_val:.0f}" if min_val != max_val else "N/A"
            print(f"已归一化 Block {i+1}, 原始深度范围(mm): {info}")
            
        return normalized_blocks
        
    @staticmethod
    def combine_normalized_blocks(normalized_blocks):
        """将归一化后的块组合成完整图像"""
        if not normalized_blocks:
            return None
            
        total_height = sum(block.shape[0] for block in normalized_blocks)
        width = normalized_blocks[0].shape[1]
        
        combined_view = np.zeros((total_height, width), dtype=np.uint8)
        current_y = 0
        
        for block in normalized_blocks:
            h_block = block.shape[0]
            combined_view[current_y:current_y + h_block, :] = block
            current_y += h_block
            
        return combined_view
        
    def display_results(self, combined_view, color_image):
        """显示处理结果"""
        if combined_view is not None:
            cv2.imshow(self.WINDOW_COMBINED, combined_view)
            
        if color_image is not None:
            cv2.imshow(self.WINDOW_COLOR, color_image)
            
    def check_exit_key(self):
        """检查退出按键"""
        key = cv2.waitKey(1) & 0xFF
        return key == self.EXIT_KEY
        
    def run(self):
        """主运行循环"""
        if not self.initialize_camera():
            return
            
        try:
            while self.running:
                # 1. 获取帧数据
                depth_image, color_image, dimensions = self.get_frames()
                if depth_image is None:
                    continue
                    
                # 2. 分割深度图
                blocks, (h, w) = self.split_depth_into_blocks(depth_image, self.NUM_BLOCKS)
                
                # 3. 归一化处理
                normalized_blocks = self.normalize_depth_blocks(blocks)
                
                # 4. 组合结果
                combined_view = self.combine_normalized_blocks(normalized_blocks)
                blurred = cv2.GaussianBlur(combined_view, (5, 5), 0)
                
                # 5. 显示结果
                self.display_results(combined_view, color_image)
                cv2.imshow("GaussianBlur",blurred)
                
                # 6. 检查退出
                if self.check_exit_key():
                    print("检测到退出键,程序结束...")
                    break
                    
        except KeyboardInterrupt:
            print("用户中断程序")
        except Exception as e:
            print(f"运行过程中发生错误: {e}")
        finally:
            self.cleanup()
            
    def cleanup(self):
        """清理资源"""
        print("正在清理资源...")
        self.stop_camera()
        cv2.destroyAllWindows()
        print("程序已安全退出")

def main():
    """主函数"""
    processor = DepthCameraProcessor()
    processor.run()

if __name__ == "__main__":
    main()

拼接图片边界线太明显,想要消除格栅
![img](https://i-blog.csdnimg.cn/ask/b16316423da247cc8ff2bfe213f84d5a.png "#left")

  • 写回答

2条回答 默认 最新

  • 紫雾凌寒 新星创作者: 人工智能技术领域 2026-01-24 12:37
    关注

    让 “紫雾凌寒” 来帮你回答,本回答结合 DeepSeek

    如果还有问题,请评论或点击头像私信,如果有帮助到您, 请关注、采纳、点赞

    1. 问题关键点分析
      - 从提供的代码片段来看,目前代码不完整,仅定义了一个类DepthCameraProcessor,但没有完整的初始化方法及处理拼接图片的相关逻辑。不过可以推测可能是在拼接图片后出现了边界线过于明显的问题。这可能是由于拼接算法、图像预处理等方面的原因导致的。
    2. 解决方案
      - 图像融合方法
      • 可以使用加权融合的方法来减少拼接边界的明显程度。例如,在拼接两张图片img1img2时,可以按照以下步骤进行:
    alpha = 0.5  # 权重,可根据实际情况调整
    beta = 1 - alpha
    img1 = cv2.imread('image1.jpg')
    img2 = cv2.imread('image2.jpg')
    # 确保两张图片尺寸相同
    height, width = img1.shape[:2]
    img2 = cv2.resize(img2, (width, height))
    dst = cv2.addWeighted(img1, alpha, img2, beta, 0.0)
    
     - 这里通过调整`alpha`和`beta`的值来控制两张图片在融合时的权重占比,从而使拼接边界更平滑。
    
    • 边缘平滑处理
      • 在拼接后,可以对拼接区域的边缘进行平滑处理。例如使用高斯模糊:
    dst = cv2.GaussianBlur(dst, (5, 5), 0)
    
     - 高斯模糊可以减少图像中的噪声,使边缘看起来更自然,减轻边界线明显的问题。
    
    • 基于特征的拼接
      • 如果使用基于特征的拼接方法(如ORB特征点匹配等),可以在匹配后对匹配点进行筛选和优化,然后再进行图像的拼接和融合。
    orb = cv2.ORB_create()
    kp1, des1 = orb.detectAndCompute(img1, None)
    kp2, des2 = orb.detectAndCompute(img2, None)
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
    matches = bf.match(des1, des2)
    matches = sorted(matches, key=lambda x: x.distance)
    good_matches = matches[:min(len(matches), 100)]
    src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
    dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
    warped = cv2.warpPerspective(img2, M, (width, height))
    # 融合之前可以对warped进行一些预处理,比如裁剪等
    # 然后再进行融合操作
    
    1. 各种方案优缺点
      - 加权融合方法
      • 优点:简单直观,容易实现,能够在一定程度上控制两张图片的融合效果。
      • 缺点:对于复杂场景的拼接,权重参数需要手动调整,可能无法达到最优效果。
      • 边缘平滑处理
      • 优点:操作简单,能有效减少边缘的突兀感,使图像整体更平滑。
      • 缺点:过度平滑可能会损失一些图像细节。
      • 基于特征的拼接
      • 优点:能更准确地找到两张图片的对应关系,拼接效果更自然,适用于各种场景。
      • 缺点:计算量较大,对特征点提取和匹配的算法要求较高,实现相对复杂。
    2. 总结
      - 拼接图片边界线过于明显是一个常见问题,可通过多种方法来解决。加权融合、边缘平滑处理和基于特征的拼接各有优缺点。在实际应用中,需要根据具体情况选择合适的方法或综合使用多种方法来达到较好的拼接效果。如果后续代码完整实现了拼接功能,可以根据实际情况进一步优化和调整上述方法的参数。

    希望以上解答对您有所帮助。如果您有任何疑问,欢迎在评论区提出。

    评论

报告相同问题?

问题事件

  • 创建了问题 1月24日