gpt4 book ai didi

python - OpenCV cv2.ellipse 扩展到更难的情况

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

我有一个掩码(不是二进制,而是 0-255 范围内的值):

enter image description here

我正在使用 cv2.fitEllipse像:

xy_arr = np.argwhere(mask>0)
xy_arr = xy_arr[:,::-1]
(center_x, center_y), (MA, ma), angle = cv2.fitEllipse(xy_arr)
cv2.ellipse(draw_image, (int(center_x), int(center_y)), (int(MA / 2), int(ma / 2)), int(angle), 0, 360, (0, 0, 255))
cv2.circle(draw_image, (int(center_x), int(center_y)), radius=1, color=(0, 0, 255), thickness=1)

结果:

enter image description here

但是,预期的结果:

enter image description here

问题:
  • 是否可以使用掩码的中间值(0-255 范围内的中间值,不仅是二进制掩码)
  • 如何克服左侧尾部的问题,是否可以根据曲率将其切断?
  • 最佳答案

    这是使用形态学来减轻 Python/OpenCV 中尾部的一种方法。

  • 阅读输入
  • 转为灰色
  • 阈值
  • 应用形态打开以平滑尾部
  • 获取非零点
  • 获取凸包点
  • 将椭圆拟合到凸包点
  • 在输入
  • 上绘制椭圆
  • 保存结果

  • 输入:

    enter image description here
    import cv2
    import numpy as np

    # read image
    img = cv2.imread('blob.png')
    hh, ww = img.shape[:2]

    # convert to grayscale
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    # threshold to binary and invert
    thresh = cv2.threshold(gray, 252, 255, cv2.THRESH_BINARY)[1]

    # apply morphology open to smooth out tail
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
    smoothed = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
    smoothed = cv2.morphologyEx(smoothed, cv2.MORPH_DILATE, kernel)

    # fit ellipse on smoothed image
    points = np.column_stack(np.where(smoothed.transpose() > 0))
    hull = cv2.convexHull(points)
    ((centx,centy), (width,height), angle) = cv2.fitEllipse(hull)

    # draw ellipse on input image
    result = img.copy()
    cv2.ellipse(result, (int(centx),int(centy)), (int(width/2),int(height/2)), angle, 0, 360, (0,0,255), 1)

    cv2.imshow('image', img)
    cv2.imshow('thresh', thresh)
    cv2.imshow('smoothed', smoothed)
    cv2.imshow('result', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # save results
    cv2.imwrite('blob_thresh.png', thresh)
    cv2.imwrite('blob_smoothed.png', smoothed)
    cv2.imwrite('blob_ellipses.png', result)

    阈值图像:

    enter image description here

    形态平滑图像:

    enter image description here

    生成的椭圆图像:

    enter image description here

    关于python - OpenCV cv2.ellipse 扩展到更难的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60921649/

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