欢迎访问宙启技术站
智能推送

在Python中实现红色水墨画风格

发布时间:2023-12-27 22:48:19

在Python中实现红色水墨画风格可以使用一些图像处理库和技术,例如OpenCV、PIL(Python Imaging Library)和numpy等。

下面是一个制作红色水墨画风格的简单示例:

首先,你需要安装所需的库。可以使用以下命令安装OpenCV和PIL库:

pip install opencv-python
pip install Pillow

然后,我们需要导入所需的库和模块:

import cv2
import numpy as np
from PIL import Image, ImageFilter

接下来,加载原始图像:

img_path = 'path_to_your_image.jpg'
img = cv2.imread(img_path)

将图像转换为灰度图像:

gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

对灰度图像进行高斯模糊处理:

blurred_img = cv2.GaussianBlur(gray_img, (21, 21), 0)

对模糊后的图像进行边缘检测处理:

edges = cv2.Canny(blurred_img, threshold1=30, threshold2=100)

接下来,我们将边缘图像转换为红色水墨画风格:

red_ink_img = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
red_ink_img[:, :, 0] = 0  # 设置蓝色通道为0
red_ink_img[:, :, 2] = 0  # 设置绿色通道为0

最后,将生成的红色水墨画风格图像保存:

output_path = 'path_to_save_output_image.jpg'
cv2.imwrite(output_path, red_ink_img)

完整的代码示例如下:

import cv2
import numpy as np
from PIL import Image, ImageFilter

# 读取图像
img_path = 'path_to_your_image.jpg'
img = cv2.imread(img_path)

# 转换为灰度图像
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 高斯模糊处理
blurred_img = cv2.GaussianBlur(gray_img, (21, 21), 0)

# 边缘检测处理
edges = cv2.Canny(blurred_img, threshold1=30, threshold2=100)

# 红色水墨画风格处理
red_ink_img = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
red_ink_img[:, :, 0] = 0  # 设置蓝色通道为0
red_ink_img[:, :, 2] = 0  # 设置绿色通道为0

# 保存输出图像
output_path = 'path_to_save_output_image.jpg'
cv2.imwrite(output_path, red_ink_img)

请将 path_to_your_image.jpg 替换为你想要处理的图像的文件路径,将 path_to_save_output_image.jpg 替换为你想要保存的输出图像的文件路径。

这是一个简单的示例,你可以根据自己的需求进行调整和改进。例如,可以尝试不同的模糊半径、边缘检测参数和颜色调整等来改变最终的效果。