如何在python中以更快的方式迭代图像像素? [英] How can i iterate over image pixels in a faster manner in python?
问题描述
我想以某种方式修改灰度图像,以便我可以将图像上半部分的像素值更改为黑色。我当然可以通过这样的常规方式迭代:
I want to modify a grayscale image in a manner so that I can change the pixel values to black for the top half of the image. I can certainly do this by iterating over in the usual manner like this:
for i in range(0,rows):
for j in range(0,cols):
if(condition)
image[i,j] = 0;
但由于我必须进行视频处理,因此速度很慢。我可以看到我必须使用 Image.point()
,但我不确定如何实现它。有人可以帮我解决这个问题吗?
But this is quite slow as I have to do video processing. I can see that I have to use Image.point()
, but I am not sure how to implement it. Can someone help me out in this?
推荐答案
如果先将PIL图像转换为numpy数组,这会快得多。以下是如何将值低于10的所有像素归零:
This will be much faster if you convert the PIL image to a numpy array first. Here's how you can zero all the pixels with a value below 10:
>>> import numpy as np
>>> arr = np.array(img)
>>> arr[arr < 10] = 0
>>> img.putdata(arr)
或者,正如你在评论中所述,这里你是黑掉的图片的上半部分:
Or, as you stated in your comment, here's you'd black out the top half of the image:
>>> arr[:arr.shape[0] / 2,:] = 0
最后,因为你'重新进行视频处理,请注意您不必遍历各个帧。假设您有10帧4x4图像:
Finally, since you're doing video processing, notice that you don't have to loop over the individual frames either. Let's say you have ten frames of 4x4 images:
>>> 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中以更快的方式迭代图像像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!