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

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

我正在使用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)

结果:

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

但是,预期结果:

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

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

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

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

  • 输入:

    python - OpenCV cv2.ellipse扩展到更困难的情况-LMLPHP
    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)
    

    阈值图片:

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

    形态平滑图像:

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

    产生的椭圆图像:

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

    10-07 18:58
    查看更多