使用python获取图像中形状的轮廓(x,y)坐标

raz*_*ool 5 python opencv numpy matplotlib

我需要用python获得一个矩阵,其中包含下图的轮廓坐标(x,y).

在此输入图像描述

我尝试使用opencv canny探测器并找到轮廓,但我得到了很多轮廓,我不知道如何得到我想要的那个.

import numpy as np
from matplotlib import pyplot as plt
import cv2
#from skimage import measure, feature, io
#from skimage import img_as_ubyte

x1 = 330
xf = 690
y1 = 0
yf = 400

img = cv2.imread('test.tif')
img = img[y1:yf, x1:xf]
edge = cv2.Canny(img, 100, 200)

image, contours, hierarchy = cv2.findContours(edge, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我只需要一个具有轮廓(x,y)坐标的数组.我认为它是在轮廓输出中,cv2.findContours()但我没有找到我想要的轮廓...

我也尝试过这个matplotlib.pyplot.contour功能:

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

img = cv2.imread('test.tif', 0) # read image
img = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)[1] # threshold image
img = cv2.medianBlur(img, 15)  # remove noise

# skeletonize 
size = np.size(img)  # get number of pixels
skel = np.zeros(img.shape, np.uint8) # create an array of zeros with the same shape as the image and 256 gray levels

element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) # create a structurant element (cross)
done = False

while(not done):
    eroded = cv2.erode(img, element)
    temp = cv2.dilate(eroded, element)
    temp = cv2.subtract(img, temp)
    skel = cv2.bitwise_or(skel, temp)
    img = eroded.copy()
    zeros = size - cv2.countNonZero(img)
    if zeros == size:
        done = True

cs = plt.contour(skel, 1)
p = cs.collections[0].get_paths()[0]
v = p.vertices
x = v[:, 0]
y = v[:, 1]
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但我只是关闭了轮廓而不是从图像的左侧到右侧的开放轮廓.

非常感谢你的回答.

Fla*_*bes 3

您几乎找到了问题的答案。首先,边缘检测和边缘检测是有区别的。轮廓检测之间存在区别。从根本上讲,边缘检测会导致您所谓的(不正确的)“开放轮廓”(即边缘),而轮廓检测会导致您所谓的“闭合轮廓”(即轮廓)。

Canny边缘检测是一种流行的边缘检测算法。由于您想要以数组形式检测边缘,其中 (x,y) 坐标从图像的左侧到右侧,因此 Canny 边缘检测是一个好主意。

答案是edge这不是所需的格式。

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

img = cv2.imread('test.tif')
edge = cv2.Canny(img, 100, 200)

ans = []
for y in range(0, edge.shape[0]):
    for x in range(0, edge.shape[1]):
        if edge[y, x] != 0:
            ans = ans + [[x, y]]
ans = np.array(ans)

print(ans.shape)
print(ans[0:10, :])
Run Code Online (Sandbox Code Playgroud)

数组ans(形状等于(n, 2))存储 (x, y) 坐标n)存储构成检测到的边缘的像素这就是您正在寻找的结果。

这是我用白色绘制这些n像素的图像:

在此输入图像描述

我希望这能帮到您。