PIL / Pillow inverts random-seeming transparency

I have Pillow 2.4.0 installed (both in virtual env on OS X and on Ubuntu 14.04 EC2). I wrote the following script to create a waveform visualization ( inspiring Jiaaro ). It uses the Pydub library to analyze waveforms and the ImageDraw function from PIL / Pillow to draw lines. The wav variable is audiosegment () (from the Pydub library), imgname is the line:

def draw_waveform(wav, imgname, color="#000000", w=400, h=40):
    sound = wav
    name = imgname
    width = w
    height = h
    color = color

    chunk_length = len(sound) / width

    loudness_of_chunks = [
        sound[ i*chunk_length : (i+1)*chunk_length ].rms
        for i in range(width)]

    max_rms = max(loudness_of_chunks)
    scale = max_rms/(height/2)

    size = (width,height)
    im = Image.new('RGBA', size, (255, 255, 255, 255))

    draw = ImageDraw.Draw(im)

    for i in range(1, width):
        pos = (width - i, height/2 + loudness_of_chunks[i]/scale-4)
        draw.line((width - i,height/2) + pos, fill=color)
        pos = (width - i, height/2 - loudness_of_chunks[i]/scale+4)
        draw.line((width - i,height/2) + pos, fill=color)

    del draw

    im.rotate(180).save(app.config['UPLOAD_FOLDER'] + '/' + name, 'GIF', transparency=0) #, transparency=0

    return app.config['UPLOAD_FOLDER'] + '/' + name

All groovy, most of the time. On some waveforms, in particular, it seems that those closest to the peak, PIL will produce a GIF that reverses the transparency — the waveform will be transparent and the space around it will be white. Usually the background is transparent and the waveform is black (# 000000).

Here is an image of the expected result:

Correct output

( save-as , , ):

Incorrect output

- ? - ()?

+4
1

, , ( ). @MarkRansom .

"P", "RGBA",

im = Image.new('P', size, 255)

( , 0)

color=0

, , :

im.save(name, 'GIF', transparency=255)

, ...

+2

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


All Articles