简体   繁体   中英

Recolor Image with Transparent Background

I'm trying to recolor (switch colors) in a photo with Python (preferably Python 3). I have a lot of geometrical shapes that have a thin black border, white fill, and a transparent background.

Here is an example input photo.

白圈

I would like to be able to generate a randomly colored circle.

I started with this code:

start_color = (0,0,0) # white
new_color = (255,255,255) # black
# Open image
shape_img = Image.open('circle_example.png').convert('RGB')
shape_data = np.array(shape_img)
# Replace start color with new color
shape_data[(shape_data == start_color).all(axis = -1)] = new_color
# Convert back to image
final_image = Image.fromarray(shape_data, mode='RGB')
final_image.show()

This results in:

final_image

Is there a way to replace just the white forefront and not the transparent background? (I realize that the transparent background appears white in this question, but if you look at the picture, it is transparent around the circle.)

I did find an answer. I need to import the alpha levels as well.

import numpy as np
from PIL import Image
start_color = (0, 0, 0, 255) # white
new_color = (255, 255, 255, 255) # black
# Open image
shape_img = Image.open('circle_example.png').convert('RGBA')
shape_data = np.array(shape_img)
# Replace start color with new color
shape_data[(shape_data == start_color).all(axis = -1)] = new_color
# Convert back to image
final_image = Image.fromarray(shape_data, mode='RGBA')
final_image.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM