如何准确获取图像中形状的轮廓?

时间:2019-06-22 23:16:57

标签: python image contour

我的黑白93x94像素图像中有几何形状。我正在尝试找到形状轮廓及其中心

这是我到目前为止尝试过的

import cv2
import imutils

img = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
blurred = cv2.GaussianBlur(img, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
for c in cnts:
    # compute the center of the contour
    M = cv2.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    # draw the contour and center of the shape on the image
    cv2.drawContours(img, [c], -1, (0, 255, 0), 2)
    cv2.circle(img, (cX, cY), 7, (0, 0, 0), -1)
    #cv2.putText(img, "center", (cX - 20, cY - 20),
        #cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)

    # show the image
    cv2.imshow('output image',img)
    cv2.waitKey(0)

这是具有给定轮廓和样本的样本输入图像和输出图像

原始图片:

original image

输出图像:

Output image

如您所见,我没有得到形状的轮廓和中心,而是得到了边界框的轮廓和中心。

关于如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:0)

经过模糊和阈值处理后,图像几乎完全变为白色。

After threasholding

我不确定对此会有什么期望。在此处使用值160做得更好

thresh = cv2.threshold(blurred, 160, 255, cv2.THRESH_BINARY)[1]

下一个问题是使用RETR_EXTERNAL,因为

  

仅提取极端的外部轮廓。

使用RETR_TREE似乎正确

  

检索所有轮廓,并重建嵌套轮廓的完整层次。