【问题标题】:How to extract coordinates from a specific contour?如何从特定轮廓中提取坐标?
【发布时间】:2018-04-03 19:52:53
【问题描述】:

我需要找到特定于轮廓的坐标,如this image 所示。我能够绘制特定的轮廓(以红色突出显示),但 .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()`

【问题讨论】:

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

标签: python coordinates opencv3.0 opencv-contour


【解决方案1】:

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

您正在绘制索引为 55 的轮廓:

area = cv2.contourArea(contours[55])

但是您对 .txt 文件的命令是:

text_file.write( "%s"% contours)

应该是这样的:

text_file.write( "%s" % contours[55] )

也就是说,如果您想获得与您绘制的相同轮廓的坐标。

我一般也建议你在编程中遵循 DRY(Don't Repeat Yourself)原则。如果您有一个常量(如 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。如果你想改变另一个轮廓,你只需要改变常量 CONTOUR。

【讨论】:

  • 我们可以用数字标记每个轮廓,然后使用上面的代码很容易找到任何特定的轮廓。请为此提供帮助
猜你喜欢
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-25
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多