gpt4 book ai didi

Python 3.7 + PIL 如何将像素着色更改为等效的 alpha 透明度级别 0-255

转载 作者:行者123 更新时间:2023-12-01 00:24:50 25 4
gpt4 key购买 nike

无法弄清楚如何将像素颜色列表转换为等效的白色 Alpha 透明度。

pixel_data = list(img.getdata())
print(pixel_data)
alpha_range = range(0, 256) # increase count
color_range = range(256, -1, -1) # decrease count
for i, pixel in enumerate(pixel_data):
if pixel[:3] == (255, 255, 255):
pixel_data[i] = (255, 255, 255, 0)
img.putdata(pixel_data)
print(list(pixel_data))

我希望解析灰度图像的像素,然后转换为等效的 Alpha 透明度级别:

.R., .G., .B. = .R., .G., .B., Alpha 
255, 255, 255 = 255, 255, 255, 0
254, 254, 254 = 255, 255, 255, 1
253, 253, 253 = 255, 255, 255, 2
252, 252, 252 = 255, 255, 255, 3
..., ..., ... = ..., ..., ..., 4
..., ..., ... = ..., ..., ..., 5
..., ..., ... = ..., ..., ..., 6
..., ..., ... = ..., ..., ..., .
..., ..., ... = ..., ..., ..., 255

我希望最终结果是全白色并具有匹配的不透明度(alpha 透明度)级别的阴影

提供了显示白色最终结果的图像。蓝色背景,方便查看: Provided image to show what the white end result should be like.  Blue background for easy viewing

最佳答案

我认为你的意思是:

import numpy as np
from PIL import Image

# Open image and ensure it has an alpha channel
im = Image.open('image.png').convert('RGBA')

# Make into Numpy array, shape [h,w,4]
ni = np.array(im)

# Set the alpha channel of each pixel to "255 - red"
ni[...,3] = 255 - ni[...,0]

# Set the RGB of each pixel to white (255,255,255)
ni[:,:,(0,1,2)] = 255

# Make back into PIL Image and save
Image.fromarray(ni).save('result.png')
<小时/>

如果由于某种原因,您反对Numpy,您可以直接在 PIL/Pillow 中执行此操作,如下所示:

#!/usr/bin/env python3

from PIL import Image

# Open image, ensuring in RGB mode, rather than palette or greyscale
im = Image.open('image.png').convert('RGB')

# Extract Red channel
R, _, _ = im.split()

# Generate Alpha channel as (255-Red)
Alpha = R.point(lambda p: 255-p)

# Fill original image with white
im.paste((255,255,255),box=(0,0,im.width,im.height))

# Add in alpha channel
im.putalpha(Alpha)

# Save
im.save('result.png')

关于Python 3.7 + PIL 如何将像素着色更改为等效的 alpha 透明度级别 0-255,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58667482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com