繁体   English   中英

在图像上垂直迭代以获取其像素索引

[英]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 33 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM