[英]How to obtain (x,y) coordinates of a shape found using mask in OpenCV, Python?
[英]How to obtain boundary coordinates of binary mask with holes?
我有以下圖像:
我想獲得一個列表,其中包含每個 blob 的外部和內部輪廓的(x, y)
坐標(我們稱它們為 blob A 和 B)。
import cv2
from skimage import measure
blob = cv2.imread('blob.png', 0)
contours, hier = cv2.findContours(blob, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
labels = measure.label(blob)
props = measure.regionprops(labels)
for ii in range(0,len(props))
xy = props[ii].coords
plt.figure(figsize=(18, 16))
plt.imshow(blob, cmap='gray')
plt.plot(xy[:, 0], xy[:,1])
plt.show()
所需的 output 圖像,其中藍色和紅色是從(x, y)
坐標列表 A 和 B 中繪制的:
您可以直接從cv2.findContours
獲得(x, y)
坐標。 要識別單個 blob,請查看層次結構hier
。 第四個索引告訴您,可能的內部(或子)輪廓與哪個外部(或父)輪廓相關。 大多數外部輪廓的索引為-1
,所有其他輪廓都具有非負值。 因此,對於繪圖/繪圖,一種天真的方法是,在迭代輪廓時,每次看到-1
時增加一個 blob 計數器,並使用相同顏色繪制所有輪廓,直到下一個-1
顯示。
import cv2
from skimage import io # Only needed for web grabbing images, use cv2.imread for local images
# Read image; find contours with hierarchy
blob = io.imread('https://i.stack.imgur.com/Ga5Pe.png')
contours, hier = cv2.findContours(blob, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Define sufficient enough colors for blobs
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
# Draw all contours, and their children, with different colors
out = cv2.cvtColor(blob, cv2.COLOR_GRAY2BGR)
k = -1
for i, cnt in enumerate(contours):
if (hier[0, i, 3] == -1):
k += 1
cv2.drawContours(out, [cnt], -1, colors[k], 2)
cv2.imshow('out', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
當然,可以使用 NumPy 優化獲得屬於同一 blob 的所有輪廓,但循環在這里感覺最直觀。 我省略了所有其他的東西(skimage、Matplotlib),因為它們在這里似乎不相關。 正如我所說, (x, y)
坐標已經存儲在contours
中。
希望有幫助!
編輯:我還沒有驗證,如果 OpenCV 總是連續獲得屬於一個最外輪廓的所有輪廓,或者如果 - 例如 - 給定層次結構級別的所有輪廓隨后存儲。 因此,對於更復雜的層次結構,這應該事先進行測試,或者應該從一開始就使用提到的使用 NumPy 的索引查找。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.