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

2025-04-26  本文已影响0人  大龙10

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

实现步骤:

二、程序

# -*- 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)

三、参数

四、扩展改进:

上一篇 下一篇

猜你喜欢

热点阅读