[英]Iterate vertically on an image to get its pixel indexes
我試圖遍歷圖像中的像素,但要垂直而不是常規的水平方式。 這是我可能擁有的小尺寸圖像的示例(我有幾百個圖像的圖像):
"""
Note: X represents pixels
Sample Image (3 x 4):
X X X X
X X X X
X X X X
"""
顯然,要在水平方向上遍歷此圖像,很容易做到,就像我在這里所做的那樣:
import itertools
width = range(3)
height = range(4)
print("Pixel positions:")
for pixel in itertools.product(width, height):
print(*pixel)
輸出:
Pixel positions:
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
這些是圖像中像素的索引位置(假定它是一個較大的2D像素列表),但水平迭代。 我希望能夠垂直執行相同的操作。 是否有itertools函數可以讓我按列執行相同的操作? 這是此示例圖像的索引:
Column-wise:
0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2
0 3
1 3
2 3
我試圖用print(*pixel[::-1])
反轉位置,但是,這會導致某些索引位置超出范圍,例如最后一個從2 3
到3 2
。 3 2
無效,因為沒有3行(僅0、1、2)。 其他職位也是如此。
我想要一個不使用非內置庫的解決方案。 Itertools很好,因為我將其用於程序中的其他內容。
試試這個代碼:
width = range(3)
height = range(4)
print("Pixel positions:")
for x in height:
for y in width:
print(y, x)
輸出:
Pixel positions:
0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2
0 3
1 3
2 3
要水平迭代,只需交換兩個for循環:
width = range(3)
height = range(4)
print("Pixel positions:")
for y in width:
for x in height:
print(y, x)
性能比較:
$ python -m timeit -n 100 '
width = range(1000)
height = range(1000)
for pixel in ((x, y) for y in height for x in width):
pass
'
100 loops, best of 3: 104 msec per loop
嵌套的for循環大約快8倍 :
$ python -m timeit -n 100 '
width = range(1000)
height = range(1000)
for y in width:
for x in height:
pass
'
100 loops, best of 3: 12.7 msec per loop
當還創建一個包含結果坐標的元組時,代碼仍然快2倍。 但是,對於手頭的任務是否需要創建一個包含坐標的元組是個問題。
$ python -m timeit -n 100 '
width = range(1000)
height = range(1000)
for y in width:
for x in height:
(x, y)
'
100 loops, best of 3: 52.5 msec per loop
根據文檔, itertools.product(width, height)
等於:
((x, y) for x in width for y in height)
如果要逐列迭代,只需交換內部循環即可:
for pixel in ((x, y) for y in height for x in width):
print(*pixel)
0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2
0 3
1 3
2 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.