我有一個影像的 numpy 陣列。我已經為我的感興趣區域設定了非零值,對于其余部分,我將值設定為 0。現在,如果我要創建一個邊界框,我可以檢查非零值的第一次出現和最后一次出現并獲取坐標。但是如果非零值在不同的地方呢?
如何創建 2 個邊界框而不是一個?
我試過了 -
A = array([[0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0]])
我期待在 Ones 周圍有 2 個邊界框。
uj5u.com熱心網友回復:
我在自己的專案中測驗了類似的代碼,但我沒有測驗這個特定的片段。如果您遇到任何錯誤,請發表評論。
import cv2
import numpy as np
A = np.array([[0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0]])
_, markers = cv2.connectedComponents(np.expand_dims(A.astype(np.uint8),axis=2),connectivity=4)
markers = np.squeeze(markers)
bounding_boxes = []
for label in range(1,int(np.max(markers)) 1):
locations = np.transpose(np.nonzero(markers==label))
min_x, max_x, min_y, max_y = np.min(locations[:,1]), np.max(locations[:,1]), np.min(locations[:,0]), np.max(locations[:,0])
bounding_boxes.append((min_x, max_x, min_y, max_y))
print(bounding_boxes)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524851.html
