[英]How to iterate through each element in a 2D array in python?
我有一個大小為 768 x 1024 的 2d numpy 數組,其中包含分段圖像的所有 class 值。 我已經在這個數組中檢測到行人/車輛,並且得到了邊界框的左上角和右下角坐標,例如(381,254)和(387,257)。
(381,254) (381,255)................ (381,257)
(382,254)
.
.
.
(387,254).................................(387,257)
這些坐標下的每個單元格都有一個特定的 class 值(數字從 1 到 22)。 我感興趣的是“4”和“10”,它們分別表示邊界框包含行人或車輛。
如何單獨遍歷每個元素(第 381 行中的所有元素從第 254 列到第 257 列然后到下一行,依此類推直到右下角坐標 (387,257))並檢查該特定單元格是否包含數字 4 或 10?
我嘗試使用嵌套的 for 循環,但我無法弄清楚邏輯。
x_1 = 381
x_2 = 387
y_1 = 254
y_2 = 257
ROW = []
COL = []
four = 0
ten = 0
other = 0
for rows in range(x_1, x_2):
ROW.append(rows)
for cols in range(y_1, y_2):
COL.append(cols)
if array[rows][cols] == 4:
four += 1
elif array[rows][cols] == 10:
ten += 1
else:
print('random number')
other += 1
任何幫助,將不勝感激。 謝謝。
嘗試改用這個:
x_1 = 381
x_2 = 387
y_1 = 254
y_2 = 257
ROW = []
COL = []
four = 0
ten = 0
other = 0
for rows in range(x_1, x_2):
ROW.append(rows)
for cols in range(y_1, y_2):
COL.append(cols)
if 4 in (x_2, y_2):
four += 1
elif 10 in (x_2, y_2):
ten += 1
else:
print('random number')
other += 1
它將檢查array[x][y]
是否包含數字 4 或 10。例如,如果array[x][y] == (12, 4)
那么four += 1
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.