美文网首页
Python:实现图像最右侧线段检测

Python:实现图像最右侧线段检测

作者: 大龙10 | 来源:发表于2025-04-26 06:48 被阅读0次

一、实现图像最右侧线段检测

实现步骤:

  • 图像预处理:转换为灰度图后使用高斯模糊降噪
  • 边缘检测:使用Canny算法检测图像边缘
  • 线段检测:通过概率霍夫变换(HoughLinesP)检测线段
  • 线段筛选:
    • 计算每条线段的右端点(最大x坐标)
    • 按右端点坐标从大到小排序
    • 选取指定数量的最右侧线段
  • 结果可视化:在原图上用绿色标出选中线段

二、程序

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 26 09:10:31 2025

实现图像最右侧线段检测  ds007.py
"""

import cv2
import numpy as np

def find_rightmost_segments(image_path, num_segments=5):
    # 读取图像
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # 高斯模糊降噪
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    
    # Canny边缘检测
    edges = cv2.Canny(blurred, 50, 150)
    
    # 霍夫变换检测线段
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=50,
                            minLineLength=10, maxLineGap=5)
    
    rightmost_lines = []
    if lines is not None:
        # 计算每条线段的右侧坐标并排序
        lines_with_right = []
        for line in lines:
            x1, y1, x2, y2 = line[0]
            right_x = max(x1, x2)
            lines_with_right.append((right_x, line))
        
        # 按右侧坐标降序排序
        lines_with_right.sort(reverse=True, key=lambda x: x[0])
        
        # 获取指定数量的最右侧线段
        selected = lines_with_right[:num_segments]
        rightmost_lines = [line for (_, line) in selected]
    
    # 在原图上绘制结果
    if rightmost_lines:
        for line in rightmost_lines:
            x1, y1, x2, y2 = line[0]
            cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
    
    return image

# 使用示例
input_image = "D:/OpenCVpic/p03.jpg"
output_image = find_rightmost_segments(input_image, num_segments=5)

# 显示并保存结果
cv2.imshow("Detected Rightmost Lines", output_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("output.jpg", output_image)

三、参数

  • num_segments:控制需要显示的线段数量
  • Canny阈值(50, 150):根据图像对比度调整
  • HoughLinesP参数:
    • threshold:检测阈值(默认50)
    • minLineLength:最小线段长度(默认50像素)
    • maxLineGap:最大线段间距(默认10像素)

四、扩展改进:

  • 增加线段间距检查,避免重复检测同一位置线段
  • 添加线段角度过滤,只保留垂直或特定方向的线段
  • 实现线段聚类,将相邻线段合并为组
  • 添加ROI(感兴趣区域)限制,只在特定区域检测

相关文章

网友评论

      本文标题:Python:实现图像最右侧线段检测

      本文链接:https://www.haomeiwen.com/subject/iixobjtx.html