繁体   English   中英

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

[英]How to extract coordinates from a specific 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.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] )

也就是说,如果要获取与绘制相同轮廓的坐标。

我通常也建议您在编程时遵循DRY(不要重复自己)原则。 如果您有一个常数(例如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()`

它将坐标写入文件contour_55.txt 如果要更改为其他轮廓,只需更改常量轮廓。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM