gpt4 book ai didi

opencv - 如何连接所有轮廓?

转载 作者:行者123 更新时间:2023-12-02 16:27:52 26 4
gpt4 key购买 nike

我需要连接外部边缘并形成一个矩形,以便它成为源图像中最大的轮廓:

enter image description here

我尝试了扩张和形态学上的接近,但对我而言不起作用。任何帮助将不胜感激!

预期产量:

enter image description here

最佳答案

大量使用 np.where 输入:

  • 沿x轴计数非零像素。获取至少具有一个非零像素的所有行的y索引。
  • 第一个索引是顶行的ymin
  • 最后一个索引是底行的ymax
  • 计算y索引之间的差异(使用 np.diff )以区分整行(而不是行)。
  • 第一个索引(映射到y个索引)是顶行的ymax
  • 最后一个索引(映射到y个索引+ 1)是底行的ymin
  • 专注于图像的顶行部分,获取非零像素的最小值和最大值,即顶行的xminxmax
  • 专注于图像的底线部分,获取非零像素的最小值和最大值,即底线的xminxmax

  • 这就是代码(使用Python API):

    import cv2
    import numpy as np
    from skimage import io # Only needed for web reading images

    # Web read image; use cv2.imread(...) for local images
    img = cv2.cvtColor(io.imread('/image/S8xJr.jpg'), cv2.COLOR_RGB2BGR)

    # Threshold grayscale version of image to get rid of JPG artifacts
    img_thr = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 128, 255, cv2.THRESH_BINARY)[1]

    # Determine min/max y values for both lines
    y_idx = np.where(np.count_nonzero(img_thr, axis=1))[0]
    line1_ymin = y_idx[0]
    line2_ymax = y_idx[-1]
    thr_inter_line = 10
    yy_idx = np.where(np.diff(y_idx) > thr_inter_line)[0]
    line1_ymax = y_idx[yy_idx[0]]
    line2_ymin = y_idx[yy_idx[-1]+1]

    # Determine min/max x values for both lines
    line1_xmin = np.min(np.where(img_thr[line1_ymin:line1_ymax, :] == 255)[1])
    line1_xmax = np.max(np.where(img_thr[line1_ymin:line1_ymax, :] == 255)[1])
    line2_xmin = np.min(np.where(img_thr[line2_ymin:line2_ymax, :] == 255)[1])
    line2_xmax = np.max(np.where(img_thr[line2_ymin:line2_ymax, :] == 255)[1])

    # Draw rectangles for both lines
    img_thr = cv2.rectangle(img_thr, (line1_xmin, line1_ymin), (line1_xmax, line1_ymax), 255, cv2.FILLED)
    img_thr = cv2.rectangle(img_thr, (line2_xmin, line2_ymin), (line2_xmax, line2_ymax), 255, cv2.FILLED)

    cv2.imshow('img', img)
    cv2.imshow('img_thr', img_thr)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    那将是输出:

    Output

    希望有帮助!

    ----------------------------------------
    System information
    ----------------------------------------
    Platform: Windows-10-10.0.16299-SP0
    Python: 3.8.1
    NumPy: 1.18.1
    OpenCV: 4.2.0
    ----------------------------------------

    关于opencv - 如何连接所有轮廓?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60187347/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com