用数字标记轮廓,然后提取任何编号轮廓的坐标

时间:2018-05-09 06:17:48

标签: python opencv contour

我需要用数字标记每个轮廓,以便在下面的代码的帮助下,我可以提取特定轮廓的坐标。

以下是图片:

import numpy as np
import cv2

THRESHOLD = 55
CONTOUR = 55

im = cv2.imread("ceramic.bmp")
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,THRESHOLD,255,0)
_th,contours, hierarchy = 
cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
print "Number of contours detected = %d" % len(contours)
cv2.drawContours(im,contours,CONTOUR,(1,70,255))
area = cv2.contourArea(contours[CONTOUR])
print (area)
cv2.imshow("Contours",im)
np.set_printoptions(threshold=np.inf)
coords = np.array2string(contours[CONTOUR])
open("contour_%d.txt" % CONTOUR, "w").write(coords)
cv2.waitKey(0)
cv2.destroyAllWindows()`

1 个答案:

答案 0 :(得分:0)

您的代码中有几点需要注意:

  1. 首先,当您想要找到轮廓时,形状必须为白色。您提供的图像具有黑暗的形状。所以我不得不反转你的图像然后找到轮廓。

  2. 其次,您只存储一个轮廓的坐标。我修改了你的代码,将每个轮廓的坐标存储在一个单独的文件中。

  3. <强>代码:

    import numpy as np
    import cv2
    
    THRESHOLD = 55
    
    path = 'C:/Users/Desktop/'
    im = cv2.imread(path + 'date.jpg')
    imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    cv2.imshow("imgray", imgray)
    
    ret, thresh = cv2.threshold(imgray, THRESHOLD, 255, 0)
    cv2.imshow('thresh', thresh)
    
    _th, contours, hierarchy = cv2.findContours(cv2.bitwise_not(thresh),     cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    print "Number of contours detected = %d" % len(contours)
    
    cv2.drawContours(im, contours, -1, (1, 70, 255), 2)
    cv2.imshow("Contours", im)
    
    contour_num = 0 
    for i in range(0, len(contours)):
        coords = np.array2string(contours[i])
        contour_num+=1
        open(path + 'contour_%d.txt' %contour_num, "w").write(coords)
    
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    按原样运行代码并查看保存的文件。