You need to enable JavaScript to run this app. 使用corner_harris、corner_peaks角点检测结果异常,如何仅检测矩形角点
优惠活动
大模型
产品
解决方案
定价
更多

使用corner_harris、corner_peaks角点检测结果异常,如何仅检测矩形角点

角点检测问题解答

原问题描述

我尝试使用corner_harris检测图像角点,但检测结果不正确,请问如何才能正确获取角点?
输入图像:
input
我使用的代码如下:

from skimage.feature import corner_harris, corner_peaks
from matplotlib import pyplot as plt
from skimage import color
from skimage.io import imread


def show_image_with_corners(image, coords, title="Corners detected"):
 plt.imshow(image, interpolation='nearest', cmap='gray')
 plt.title(title)
 plt.plot(coords[:, 1], coords[:, 0], '+r', markersize=15)
 plt.axis('off')
    

def show_image(image, title='Image', cmap_type='gray'):
 plt.imshow(image, cmap=cmap_type)
 plt.title(title)
 
read_image = imread('test_img.png')

# Convert image from RGB to grayscale
 img_gray = color.rgb2gray(read_image )
# Apply the detector to measure the possible corners
measure_image = corner_harris(img_gray)

# Find the peaks of the corners using the Harris detector
coords = corner_peaks(measure_image, min_distance=5, threshold_rel=0.02)
show_image_with_corners(img_gray, coords)

当前得到的输出结果:
output
请问如何仅检测图像中的矩形?另外corner_peaks(measure_image, min_distance=5, threshold_rel=0.02)的参数设置有什么优化建议?要怎么做才能仅检测到矩形的角点?


解决方法

问题原因

当前检测结果出现大量多余角点,核心是两个问题:一是没有过滤背景纹理,背景的细碎纹理被识别成了假角点;二是corner_peaks参数设置不合理,阈值太低、最小距离太小,把弱响应的无效点也保留了下来。

优化步骤

  1. 先做图像二值化,把前景矩形和背景完全分开,从根源上避免背景区域产生无效角点
  2. 调整corner_peaks参数,适配当前图像的矩形尺寸
  3. 可选:如果需要更精准的结果,可以先提取轮廓,只对矩形轮廓做角点检测

优化后可运行代码

from skimage.feature import corner_harris, corner_peaks
from matplotlib import pyplot as plt
from skimage import color, io, filters


def show_image_with_corners(image, coords, title="Corners detected"):
    plt.imshow(image, interpolation='nearest', cmap='gray')
    plt.title(title)
    plt.plot(coords[:, 1], coords[:, 0], '+r', markersize=15)
    plt.axis('off')


if __name__ == '__main__':
    read_image = io.imread('test_img.png')
    # 转灰度图
    img_gray = color.rgb2gray(read_image)
    # 二值化分离前景和背景
    thresh = filters.threshold_otsu(img_gray)
    binary_img = img_gray > thresh
    # 基于二值图做Harris角点检测
    measure_image = corner_harris(binary_img)
    # 调整参数:最小距离设为20(适配矩形角点的间距),相对阈值提高到0.1过滤弱响应点
    coords = corner_peaks(measure_image, min_distance=20, threshold_rel=0.1)
    show_image_with_corners(img_gray, coords)
    plt.show()

参数调整建议

  • min_distance:单位是像素,代表两个角点之间允许的最小距离。当前图像里矩形的角点间距都在几十像素以上,设置为15~30即可,避免同一个角点周围检出多个重复点。
  • threshold_rel:取值范围01,代表保留的角点响应值和最高响应值的比例。数值越高,只保留响应越强的角点,原设置0.02过低,调整到0.080.2区间即可过滤掉绝大多数假角点。

如果调整参数后还有少量多余角点,可以再加一步轮廓检测,先提取图像中面积最大的矩形轮廓,再只在轮廓范围内做角点检测,就能完全避免其他区域的干扰。


内容的提问来源于stack exchange,提问作者Mary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 08:45:03