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;
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?
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
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.]],
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With