From a92322b7946ff4c1378932e4f14cf109de166f80 Mon Sep 17 00:00:00 2001 From: iou1name Date: Sat, 16 Dec 2017 01:57:48 -0500 Subject: [PATCH] replaced alpha composite function --- ascii.py | 49 +++++++++---------------------------------------- 1 file changed, 9 insertions(+), 40 deletions(-) diff --git a/ascii.py b/ascii.py index 6e13a5d..9cee3bf 100755 --- a/ascii.py +++ b/ascii.py @@ -37,7 +37,7 @@ def scale_image(image, maxDim=100): new_height = maxDim aspect_ratio = original_width/float(original_height) new_width = int(aspect_ratio * new_height) - image = image.resize((new_width, new_height), Image.ANTIALIAS) + image = image.resize((new_width, new_height)) return image @@ -141,46 +141,15 @@ def open_image(imagePath): return image -def alpha_composite(front, back): - """Alpha composite two RGBA images. - +def alpha_composite(image, color=(255, 255, 255)): + """ + Alpha composite an RGBA Image with a specified color. Source: http://stackoverflow.com/a/9166671/284318 - - Keyword Arguments: - front -- PIL RGBA Image object - back -- PIL RGBA Image object - """ - front = np.asarray(front) - back = np.asarray(back) - result = np.empty(front.shape, dtype='float') - alpha = np.index_exp[:, :, 3:] - rgb = np.index_exp[:, :, :3] - falpha = front[alpha] / 255.0 - balpha = back[alpha] / 255.0 - result[alpha] = falpha + balpha * (1 - falpha) - old_setting = np.seterr(invalid='ignore') - result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha] - np.seterr(**old_setting) - result[alpha] *= 255 - np.clip(result, 0, 255) - # astype('uint8') maps np.nan and np.inf to 0 - result = result.astype('uint8') - result = Image.fromarray(result, 'RGBA') - return result - - -def alpha_composite_with_color(image, color=(255, 255, 255)): - """Alpha composite an RGBA image with a single color image of the - specified color and the same size as the original image. - - Keyword Arguments: - image -- PIL RGBA Image object - color -- Tuple r, g, b (default 255, 255, 255) - - """ - back = Image.new('RGBA', size=image.size, color=color + (255,)) - return alpha_composite(image, back) + image.load() # needed for split() + background = Image.new('RGB', image.size, color) + background.paste(image, mask=image.split()[3]) # 3 is the alpha channel + return background def image_to_ascii(image=None, reverse=False, brail=False, color=None,**kwargs): @@ -195,7 +164,7 @@ def image_to_ascii(image=None, reverse=False, brail=False, color=None,**kwargs): if image.mode == "P": image = image.convert(image.palette.mode) if image.mode == "RGBA": - image = alpha_composite_with_color(image).convert("RGB") + image = alpha_composite(image).convert("RGB") image = scale_image(image)