OPenCV:如何获取图像周围的周长坐标

OPenCV : How to get the perimeter coordinates around image

希望使用 Python 和 Opencv 在 x,y 坐标中提取此图像周围的折线周长

这是我目前所做的 def api():

# Reading image 
# variable and converting to gray scale. 
img = cv2.imread('floorplan.jpg', cv2.IMREAD_GRAYSCALE) 

# Converting image to a binary image 
# ( black and white only image). 
_, threshold = cv2.threshold(img, 110, 255, cv2.THRESH_BINARY) 

# Detecting contours in image. 
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, 
                            cv2.CHAIN_APPROX_SIMPLE) 
all = []
for c in contours:
    if cv2.contourArea(c) <= 200 :
       continue    
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255,0), 2)
    center = (x,y)
    all.append(center)
print(all)

我解决您的问题的方法是尝试对您正在寻找的整个周长设置阈值。为此,我找到了图像中的背景颜色,并用它来过滤原始图像并侵蚀选区以使其稍微变大并移除一些伪像。 然后,类似于您的代码,找到轮廓,删除较小的轮廓并将每个轮廓近似为多边形。一旦你有了这个近似值,你就可以简单地把它画成一个等高线,这是非常有效的。 为了计算近似值,我使用与原始轮廓周长的 3% 差异,计算如下:每个轮廓的 cv2.arcLength(c, True)

mask = cv2.inRange(img, np.array([240, 240, 240]), np.array([244, 244, 244]))
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
newmask = cv2.morphologyEx(mask, cv2.MORPH_ERODE, kernel, iterations=2)

contours, hierarchy = cv2.findContours(~newmask, cv2.RETR_TREE, 
                        cv2.CHAIN_APPROX_SIMPLE) 

output = np.zeros_like(img[:, :, 0])
for c in [c for c in contours if cv2.contourArea(c) > 200]:
    approx = cv2.approxPolyDP(c, 0.03*cv2.arcLength(c, True), True)
    cv2.drawContours(output, [approx], -1, 255, 2)
plt.imshow(output, 'gray')