如何在python中以更快的方式迭代图像像素?

Aru*_*ham 2 python image-processing python-imaging-library

我想以某种方式修改灰度图像,以便我可以将图像的上半部分的像素值更改为黑色.我当然可以通过这样的常规方式迭代来做到这一点:

for i in range(0,rows):
  for j in range(0,cols):
    if(condition)
      image[i,j] = 0;
Run Code Online (Sandbox Code Playgroud)

但由于我必须进行视频处理,因此速度很慢.我可以看到我必须使用Image.point(),但我不确定如何实现它.有人可以帮助我吗?

Joh*_*ard 8

如果您首先将PIL图像转换为numpy数组,这将会快得多.以下是如何将值低于10的所有像素归零:

>>> import numpy as np
>>> arr = np.array(img)
>>> arr[arr < 10] = 0
>>> img.putdata(arr)
Run Code Online (Sandbox Code Playgroud)

或者,正如您在评论中所述,这里是您将图像的上半部分涂黑:

>>> arr[:arr.shape[0] / 2,:] = 0
Run Code Online (Sandbox Code Playgroud)

最后,由于您正在进行视频处理,请注意您不必遍历各个帧.假设您有10帧4x4图像:

>>> arr = np.ones((10,4,4)) # 10 all-white frames
>>> arr[:,:2,:] = 0         # black out the top half of every frame
>>> a
array([[[ 0.,  0.,  0.,  0.],
    [ 0.,  0.,  0.,  0.],
    [ 1.,  1.,  1.,  1.],
    [ 1.,  1.,  1.,  1.]],

   [[ 0.,  0.,  0.,  0.],
    [ 0.,  0.,  0.,  0.],
    [ 1.,  1.,  1.,  1.],
    [ 1.,  1.,  1.,  1.]],
...
Run Code Online (Sandbox Code Playgroud)