Python 如何从特定轮廓提取坐标?

Python 如何从特定轮廓提取坐标?,python,coordinates,opencv3.0,opencv-contour,Python,Coordinates,Opencv3.0,Opencv Contour,我需要找到特定于等高线的坐标,如中所示。我能够绘制特定轮廓(以红色突出显示),但是.txt文件给出了相同的坐标集,即使我正在更改轮廓 import numpy as np import cv2 im = cv2.imread("ceramic.bmp") imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,55,255,0) _th,contours, hierarchy = cv2.fi

我需要找到特定于等高线的坐标,如中所示。我能够绘制特定轮廓(以红色突出显示),但是
.txt
文件给出了相同的坐标集,即使我正在更改轮廓

import numpy as np
import cv2
im = cv2.imread("ceramic.bmp")
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,55,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,55,(1,70,255)) #-1 fills it
area = cv2.contourArea(contours[55])
print (area)
cv2.imshow("Contours",im)
text_file = open("contour_list_55.txt", "w")    ##### Write the 
coordinates (x,y) of a contour in an txt file python 
text_file.write( "%s"% contours) 
text_file.close()
cv2.waitKey(0)
cv2.destroyAllWindows()`

这是因为您正在将所有轮廓写入文件,而不仅仅是单个轮廓

您正在绘制索引为55的等高线:

area = cv2.contourArea(contours[55])
但是您对.txt文件的命令是:

text_file.write( "%s"% contours)
应该是这样的:

text_file.write( "%s" % contours[55] )
也就是说,如果你想得到你画的同一个轮廓的坐标

我还通常建议您在编程时遵循干燥(不要重复)原则。如果你有一个常数(比如55),你应该定义它并在你的代码中使用它的名字。例如:

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()`

它将坐标写入文件
等高线_55.txt
。如果您想更改为另一个轮廓,只需更改恒定轮廓。

我们可以用数字标记每个轮廓,然后使用上述代码很容易找到任何特定轮廓。我们可以用数字标记每个轮廓,然后用上面的代码很容易找到任何特定轮廓。请帮忙