从 openCV 轮廓创建路径

Create path from openCV contour

你好,我想在这个 video 中做一些类似的事情。在 V-rep 系统中使用 python API,现在我的机器人正在工作,只需要处理我想绘制的图像。

为此,我需要一个笔路径的 (x,y) 坐标向量。所以我正在尝试使用 OpenCV findContours 函数。这是我的代码:

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('img.jpg', 3)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

edges,contours,hierarchy = cv2.findContours(gray, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

xList = [x[0][0][0] for x in contours]
yList = [y[0][0][1] for y in contours]

#plot image
plt.subplot(121)
plt.imshow(img,cmap = 'gray')
plt.title('Original Image') 

#plot contour
plt.subplot(122)
plt.plot(xList,yList)
plt.title('Edge Image')

plt.show()

这是我的示例图片:

以及如果我使用散点图单独绘制每个点的结果显示图像的轮廓。

好吧,这可能不是我第一次使用 OpenCV 查找轮廓的最佳示例。

如果我使用 plot 函数绘制点,以查看我想要遵循的路径,我会得到:

所以我想要的是找到一种方法,将连续顺序路径上的所有点排序以绘制图像轮廓。

这里的问题是点未排序,因此 don 与它的前一个点和下一个点有关系,它们只是点云。所以我需要对其进行排序以构建路径。

知道怎么做吗?

我发现 this thread 让我有了使用 matplotlib 和 contour 函数的想法,我调试它并找到它用来在 allsegs [=19 中绘制的数据=],这暂时解决了我的问题,也许它不是最好的解决方案,但现在它有效。

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('img.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# gray = cv2.bilateralFilter(gray, 50, 50, 10)
edged = cv2.Canny(gray, 70, 250)

#plot image
plt.subplot(1,3,1)
plt.imshow(img, cmap='gray')

#plot contour
plt.subplot(1,3,2)
a = plt.contour(edged, levels=[255], colors='black', origin='image')

#plot separated contour
plt.subplot(1,3,3)
for i in range(len(a.allsegs[0])):
    x = a.allsegs[0][i][:,0]
    y = a.allsegs[0][i][:,1]
    plt.plot(x,y)

plt.show()

1. 你想创建这样的:

基本步骤是:

  1. Read and convert to gray,
  2. Threshold to binary image
  3. Do findContours on binary-imaget
  4. Then drawContours, you'll get it.

2.如果你想得到这样的想法:

基本步骤是:

  1. Read and convert to gray
  2. Blur and do Canny
  3. Find by connectedComponents
  4. Then set the labels to different colors
  5. You will get like that.


生成最后一张图片的代码:

#!/usr/bin/python3
# 2018.01.23 11:25:35 CST
# 2018.01.23 11:45:22 CST

import numpy as np
import cv2
import myutils

colors = [(0, 0, 255), (0, 43, 255), (0, 85, 255), (0, 128, 255), (0, 170, 255), (0, 213, 255), (0, 255, 255), (0, 255, 212), (0, 255, 170), (0, 255, 127), (0, 255, 85), (0, 255, 42), (0, 255, 0), (43, 255, 0), (85, 255, 0), (128, 255, 0), (170, 255, 0), (213, 255, 0), (255, 255, 0), (255, 212, 0), (255, 170, 0), (255, 127, 0), (255, 85, 0), (255, 42, 0), (255, 0, 0)]

img = cv2.imread("leaf.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(img, 3)
edged = cv2.Canny(gray, 50, 200)

## Find connected edges
ret, labels = cv2.connectedComponents(edged)

## Draw(set to different colors)
canvas = np.zeros_like(img, np.uint8)
for i in range(1,ret):
    pts = labels == i
    canvas[pts] = colors[i%len(colors)]

## Display
cv2.imshow("res", canvas);cv2.waitKey();cv2.destroyAllWindows()
cv2.imwrite("res.png", canvas)

但是Notice,我设置不同颜色的边,而the points of different colors maybe not the real path.