【问题标题】:OpenCV Find a middle line of a contour [Python]OpenCV查找轮廓的中间线[Python]
【发布时间】:2021-01-31 09:22:21
【问题描述】:

在我的图像处理项目中,我已经使用cv.findContours 函数获得了蒙版图像(黑白图像)及其轮廓。我现在的目标是创建一个可以为该轮廓绘制中间线的算法。蒙版图像及其轮廓如下图所示。

蒙面图片:

轮廓:

在我的想象中,对于那个轮廓,我想创建一条接近水平的中间线。我已经手动将我的理想中线标记为红色。请检查下图中我提到的红色中间线。

中线轮廓:

值得注意的是,我的最终目标是找到我用黄色标记的尖端。如果您有其他可以直接找到黄色提示点的想法,也请告诉我。为了找到黄色提示点,我尝试了两种方法cv.convexHullcv.minAreaRect,但问题是稳健性。我使这两种方法适用于某些图像,但对于我数据集中的其他一些图像,它们效果不佳。因此,我认为找到中间线可能是一个我可以尝试的好方法。

【问题讨论】:

  • 你可以使用形态学。请在这里查看我的答案stackoverflow.com/questions/22058485/…。您也可以在这里查看:docs.opencv.org/3.4/d1/dee/tutorial_introduction_to_pca.html
  • 使用 minAreaRect 计算围绕区域旋转的矩形。这将为您提供 4 个角和方向角。然后,您可以从 4 个角计算中线并画一条线。
  • @fmw42 感谢您的回复。在问这个问题之前,我已经尝试过cv.minAreaRect。对于我的数据集中的一些图像,计算出的矩形不在我想要的方向。例如,如果该对象位于图像区域的角落,则计算出的 min-area-rect 将类似于正方形,并且其方向不准确。

标签: python opencv image-processing opencv-contour


【解决方案1】:

这是另一种方法,通过在 Python/OpenCV 中计算围绕您的对象的旋转边界框的中心线。

输入:

import cv2
import numpy as np

# load image
img = cv2.imread("blob_mask.jpg")

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

# threshold the grayscale image
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# get coordinates of all non-zero pixels
# NOTE: must transpose since numpy coords are y,x and opencv uses x,y
coords = np.column_stack(np.where(thresh.transpose() > 0))

# get rotated rectangle from 
rotrect = cv2.minAreaRect(coords)
box = cv2.boxPoints(rotrect)
box = np.int0(box)
print (box)

# get center line from box
# note points are clockwise from bottom right
x1 = (box[0][0] + box[3][0]) // 2
y1 = (box[0][1] + box[3][1]) // 2
x2 = (box[1][0] + box[2][0]) // 2
y2 = (box[1][1] + box[2][1]) // 2

# draw rotated rectangle on copy of img as result
result = img.copy()
cv2.drawContours(result, [box], 0, (0,0,255), 2)
cv2.line(result, (x1,y1), (x2,y2), (255,0,0), 2)

# write result to disk
cv2.imwrite("blob_mask_rotrect.png", result)

# display results
cv2.imshow("THRESH", thresh)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

【讨论】:

    【解决方案2】:

    我相信您正在尝试确定轮廓的重心和方向。我们可以使用Central Moments 轻松做到这一点。更多关于here的信息。

    下面的代码生成this plot。这是你想要的结果吗?

    # Determine contour
    img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)
    img_bin = (img>128).astype(np.uint8)
    contours, _ = cv2.findContours(img_bin, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
    
    # Determine center of gravity and orientation using Moments
    M = cv2.moments(contours[0])
    center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
    theta = 0.5*np.arctan2(2*M["mu11"],M["mu20"]-M["mu02"])
    endx = 600 * np.cos(theta) + center[0] # linelength 600
    endy = 600 * np.sin(theta) + center[1]
    
    # Display results
    plt.imshow(img_bin, cmap='gray')
    plt.scatter(center[0], center[1], marker="X")
    plt.plot([center[0], endx], [center[1], endy])
    plt.show()
    

    【讨论】:

      【解决方案3】:

      我现在的目标是创建一个算法,可以为这个轮廓画一条中间线。

      如果检测到水平线的上限和下限,则可以计算中线坐标。

      例如:

      中间线将是:

      如果将大小更改为图像的宽度:

      代码:


      import cv2
      
      img = cv2.imread("contour.jpg")
      gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
      (h, w) = img.shape[:2]
      
      x1_upper = h
      x1_lower = 0
      x2_upper = h
      x2_lower = 0
      y1_upper = h
      y1_lower = 0
      y2_upper = h
      y2_lower = 0
      
      lines = cv2.ximgproc.createFastLineDetector().detect(gray)
      
      for cur in lines:
          x1 = cur[0][0]
          y1 = cur[0][1]
          x2 = cur[0][2]
          y2 = cur[0][3]
      
          # upper-bound coords
          if y1 < y1_upper and y2 < y2_upper:
              y1_upper = y1
              y2_upper = y2
              x1_upper = x1
              x2_upper = x2
          elif y1 > y1_lower and y2 > y2_lower:
              y1_lower = y1
              y2_lower = y2
              x1_lower = x1
              x2_lower = x2
      
      
      print("\n\n-lower-bound-\n")
      print("({}, {}) - ({}, {})".format(x1_lower, y1_lower, x2_lower, y2_lower))
      print("\n\n-upper-bound-\n")
      print("({}, {}) - ({}, {})".format(x1_upper, y1_upper, x2_upper, y2_upper))
      
      cv2.line(img, (x1_lower, y1_lower), (x2_lower, y2_lower), (0, 255, 0), 5)
      cv2.line(img, (x1_upper, y1_upper), (x2_upper, y2_upper), (0, 0, 255), 5)
      
      x1_avg = int((x1_lower + x1_upper) / 2)
      y1_avg = int((y1_lower + y1_upper) / 2)
      x2_avg = int((x2_lower + x2_upper) / 2)
      y2_avg = int((y2_lower + y2_upper) / 2)
      
      cv2.line(img, (0, y1_avg), (w, y2_avg), (255, 0, 0), 5)
      
      cv2.imshow("result", img)
      cv2.waitKey(0)
      cv2.destroyAllWindows()
      

      【讨论】:

        猜你喜欢
        • 2012-12-28
        • 1970-01-01
        • 1970-01-01
        • 2017-11-11
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        • 1970-01-01
        • 2012-02-25
        相关资源
        最近更新 更多