簡體   English   中英

使用python獲取圖像中形狀的輪廓(x,y)坐標

[英]Get a contour (x,y) coordinates of a shape in an image with python

我需要用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)

在此輸入圖像描述

我只需要一個具有輪廓(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]

在此輸入圖像描述

但我只是關閉了輪廓而不是從圖像的左側到右側的開放輪廓。

非常感謝你的回答。

你幾乎找到了問題的答案。 首先, 邊緣檢測輪廓檢測之間存在差異。 從根本上說,邊緣檢測會導致您所謂的(不正確)“開放輪廓”(即邊緣),並且輪廓檢測會產生您所謂的“閉合輪廓”(即輪廓)。

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, :])

數組ans (形狀等於(n, 2) )存儲構成檢測到的邊緣的n像素的(x,y)坐標。 這是您正在尋找的結果。

這是一張圖像,我用白色繪制了這n像素:

在此輸入圖像描述

我希望這能幫到您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM