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

标签 python image-processing python-imaging-library

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

for i in range(0,rows):
  for j in range(0,cols):
    if(condition)
      image[i,j] = 0;

但这很慢,因为我必须进行视频处理。我可以看到我必须使用 Image.point(),但我不确定如何实现它。有人可以帮我解决这个问题吗?

最佳答案

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

>>> import numpy as np
>>> arr = np.array(img)
>>> arr[arr < 10] = 0
>>> img.putdata(arr)

或者,正如您在评论中所述,您可以将图片的上半部分涂黑:

>>> arr[:arr.shape[0] / 2,:] = 0

最后,由于您正在进行视频处理,请注意您也不必遍历各个帧。假设您有十帧 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.]],
...

关于python - 如何在 python 中以更快的方式迭代图像像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13461153/

相关文章:

python - 根据 csv 字段在数据框中创建列

python - 在 Selenium 中抓取多个 URL 并写入 JSON

python - 如何删除重叠的轮廓并将每个字符分离为单独的轮廓以提取字符?

python - 无法使用 im.getcolors

python-3.x - 更改 ndarray 的维度并乘以内容

python - 从 JPEG 或 png 文件中获取绘图数据

python - 如何减少 if/elif 语句中的重复代码

python - 我可以在 pygtk 中为 gtk 滚动条使用我自己的 css 样式吗?

Python,opencv matchtemplate错误

c++ - OpenCV 无法使用 imwrite 写入图像