使用python实现炫酷的渐变色

1、前言

通过应用颜色渐变,可以大大提升图像的视觉效果。在这篇博客中,我们将演示如何使用Python和PIL库将水平渐变应用于与目标颜色匹配的图像。

初始图片
初始图片
经过渐变色效果
在这里插入图片描述

2、所需条件

要跟随本教程,您需要:

  • 在您的机器上安装Python。
  • 安装PIL(Pillow)库,可以使用命令 pip install pillow 进行安装。

3、实现步骤

步骤1:定义渐变函数

首先,我们需要一个函数来生成两个指定颜色之间的渐变颜色。此函数将接收起始颜色、结束颜色以及渐变步骤(或图像宽度)来生成渐变。

from PIL import Image

def gradient_color(start_color, end_color, steps):
    """
    生成从start_color到end_color之间的渐变颜色。
    """
    # 将RGB颜色转换为浮点数
    start_color = [float(c) for c in start_color]
    end_color = [float(c) for c in end_color]

    # 计算每个通道的颜色步长
    step_size = [(end - start) / steps for start, end in zip(start_color, end_color)]

    # 生成渐变颜色
    gradient = []
    for i in range(steps):
        color = [int(start + step * i) for start, step in zip(start_color, step_size)]
        gradient.append(tuple(color))

    return gradient

步骤2:将渐变应用于目标颜色

接下来,我们将编写一个函数,将生成的渐变应用于图像。该函数将更改在指定容差内与目标颜色匹配的像素的颜色。

def apply_gradient_to_specific_color(image_path, target_color, tolerance, start_color, end_color):
    """
    将水平渐变从start_color到end_color应用于与target_color匹配的像素。
    """
    # 打开图像
    image = Image.open(image_path)
    # 转换图像为RGB模式
    image = image.convert('RGB')
    # 获取图像尺寸
    width, height = image.size

    # 根据宽度生成渐变颜色
    gradient_colors = gradient_color(start_color, end_color, width)

    # 创建一个新的空白图像以应用渐变
    gradient_image = Image.new('RGB', (width, height))

    # 根据像素的x位置将渐变颜色应用于与目标颜色匹配的像素
    pixels = gradient_image.load()
    original_pixels = image.load()
    for y in range(height):
        for x in range(width):
            original_pixel = original_pixels[x, y]
            # 检查原始像素颜色是否在目标颜色的容差范围内
            if all(abs(original_pixel[channel] - target_color[channel]) <= tolerance for channel in range(3)):
                color = gradient_colors[x]
            else:
                color = original_pixel
            pixels[x, y] = color

    return gradient_image

步骤3:定义参数并执行

现在,我们可以定义目标颜色、容差、渐变的起始和结束颜色,并将我们的函数应用于图像

在这里插入代码片# 定义目标颜色、容差和渐变颜色
target_color = (0, 0, 0)  # 黑色
tolerance = 50
start_color = (100, 100, 100)  # 渐变起始颜色
end_color = (200, 200, 200)    # 渐变结束颜色

# 将渐变应用于图像
result_image = apply_gradient_to_specific_color("input_image.jpg", target_color, tolerance, start_color, end_color)
result_image.save("output_image.jpg")

4、完整代码

from PIL import Image


def gradient_color(start_color, end_color, steps):
    """
    Generate a gradient of colors between start_color and end_color.
    """
    # Convert RGB colors to floating point
    start_color = [float(c) for c in start_color]
    end_color = [float(c) for c in end_color]

    # Calculate color step size for each channel
    step_size = [(end - start) / steps for start, end in zip(start_color, end_color)]

    # Generate gradient colors
    gradient = []
    for i in range(steps):
        color = [int(start + step * i) for start, step in zip(start_color, step_size)]
        gradient.append(tuple(color))

    return gradient


def apply_gradient_to_specific_color(image_path, target_color, tolerance, start_color, end_color):
    """
    Apply a horizontal gradient from start_color to end_color to pixels matching the target_color.
    """
    # Open image
    image = Image.open(image_path)
    # Convert image to RGB
    image = image.convert('RGB')
    # Get image size
    width, height = image.size

    # Generate gradient colors based on width
    gradient_colors = gradient_color(start_color, end_color, width)

    # Create a new blank image to apply gradient
    gradient_image = Image.new('RGB', (width, height))

    # Apply gradient color to each pixel based on its x position if it matches the target color
    pixels = gradient_image.load()
    original_pixels = image.load()
    for y in range(height):
        for x in range(width):
            original_pixel = original_pixels[x, y]
            # Check if the original pixel color is within the tolerance range of the target color
            if all(abs(original_pixel[channel] - target_color[channel]) <= tolerance for channel in range(3)):
                color = gradient_colors[x]
            else:
                color = original_pixel
            pixels[x, y] = color

    return gradient_image


# Define target color, tolerance, and gradient colors
target_color = (0, 0, 0)  # White
tolerance = 50
start_color = (100, 100, 100)  # Red
end_color =  (200, 200, 200) # Blue

# Apply gradient to image
result_image = apply_gradient_to_specific_color("input_image.jpg", target_color, tolerance, start_color, end_color)
result_image.save("output_2.jpg")

5、总结

在这篇博客中,我们演示了如何使用Python和PIL库将水平渐变应用于图像中的特定颜色。欢迎您尝试使用不同的目标颜色、渐变和容差值,以实现您在图像上的理想效果。编程愉快!

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扬志九洲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值