Using the Image.point() method in PIL to manipulate pixel data

前端 未结 2 1571
抹茶落季
抹茶落季 2020-12-08 15:28

I am using the Python Imaging Library to colorize a black and white image with a lookup table that defines the color relationships. The lookup table is simply a 256-element

相关标签:
2条回答
  • 2020-12-08 16:16

    I think it might be more typical to point on a band-by-band basis like so (lifted directly from the PIL tutorial):

    # split the image into individual bands
    source = im.split()
    
    R, G, B = 0, 1, 2
    
    # select regions where red is less than 100
    mask = source[R].point(lambda i: i < 100 and 255)
    
    # process the green band
    out = source[G].point(lambda i: i * 0.7)
    
    # paste the processed band back, but only where red was < 100
    source[G].paste(out, None, mask)
    
    # build a new multiband image
    im = Image.merge(im.mode, source)
    
    0 讨论(0)
  • 2020-12-08 16:26

    Is Image.point() the right tool for this job?

    Yes indeed, Image.point() is perfect for this job

    What format/structure does Image.point() expect the table?

    You should flatten the list so instead of [(12, 140, 10), (10, 100, 200), ...] use:

    [12, 140, 10, 10, 100, 200, ...]
    

    Here is a quick example I just tried:

    im = im.point(range(256, 0, -1) * 3)
    

    alt text alt text

    And by the way, if you need more control over colors and you feel Image.point is not for you you can also use Image.getdata and Image.putdata to change colors more quickly than both load and putpixel. It is slower than Image.point though.

    Image.getdata gives you the list of all pixels, modify them and write them back using Image.putdata. It is that simple. But try to do it using Image.point first.


    EDIT

    I made a mistake in the first explanation, I'll explain correctly now:

    The color table actually is like this

    [0, 1, 2, 3, 4, 5, ...255, 0, 1, 2, 3, ....255, 0, 1, 2, 3, ...255]
    

    Each band range next to the other. To change the color (0, 0, 0) to (10, 100, 10) it need to become like this:

    [10, 1, 2, 3, 4, 5, ...255, 100, 1, 2, 3, ....255, 10, 1, 2, 3, ...255]
    

    To transform your color list into the right format try this:

    table = sum(zip(*colors), ())
    

    I think my first example should demonstrate the formate for you.

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