How can i iterate over image pixels in a faster manner in python?

后端 未结 2 1283
误落风尘
误落风尘 2020-12-20 03:16

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

相关标签:
2条回答
  • 2020-12-20 03:46

    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.]],
    ...
    
    0 讨论(0)
  • 2020-12-20 03:58

    This is a very good candidate for multiprocessing the image/s. If you split the image into blocks of pixels you can very easily process the image in parallel, that is if it is sufficiently large or you are doing this on a lot of images.

    1. Break the image up into chunks defined as tuples ( top left X, top left Y, width, height )
    2. Pass tuples and image handle to various threads, hopefully in a thread pool.
    3. Wait for threads to finish and then continue using your image.

    This, depending on the image size and your pick of the number of threads and block size, can speed up your process linearly up to a point of course.

    0 讨论(0)
提交回复
热议问题