Is there an Image.point () method in PIL that allows you to work on all three channels at the same time?

I want to write a point filter that is based on red, green and blue channels for each pixel, but it seems that this may not match the capabilities point()- it seems that it works on one pixel in one channel at a time. I would like to do something like this:

def colorswap(pixel):
    """Shifts the channels of the image."""
    return (pixel[1], pixel[2], pixel[0])
image.point(colorswap)

Is there an equivalent method that allows me to use a filter that takes a 3-tuple of RGB values ​​and outputs a new 3-tuple?

+3
source share
2 answers

You can use the method loadfor quick access to all pixels.

def colorswap(pixel):
    """Shifts the channels of the image."""
    return (pixel[1], pixel[2], pixel[0])

def applyfilter(image, func):
    """ Applies a function to each pixel of an image."""
    width,height = im.size
    pixel = image.load()
    for y in range(0, height):
        for x in range(0, width):
            pixel[x,y] = func(pixel[x,y])

applyfilter(image, colorswap)
+2

, , "".

numpy :

def colorswap(pixel):
    """Shifts the channels of the image."""
    return (pixel[1], pixel[2], pixel[0])

def npoint(img, func):
    import numpy as np
    a = np.asarray(img).copy()
    r = a[:,:,0]
    g = a[:,:,1]
    b = a[:,:,2]
    r[:],g[:],b[:] = func((r,g,b))
    return Image.fromarray(a,img.mode)

img = Image.open('test.png')
img2 = npoint(img, colorswap)
img2.save('test2.png')

: , Image , , npoint point ( , ):

Image.Image.npoint = npoint

img = Image.open('test.png')
img2 = img.npoint(colorswap)
+2

Source: https://habr.com/ru/post/1782056/


All Articles