Python实现PS滤镜的旋转模糊功能示例
作者:野牛程序员:2023-11-28 12:00:03python阅读 2857
使用Python中的OpenCV库可以实现PS滤镜的旋转模糊功能。以下是一个简单的示例代码:
import cv2 import numpy as np def rotate_blur(image_path, output_path, angle, strength): # 读取图像 image = cv2.imread(image_path) # 获取图像的中心坐标 height, width = image.shape[:2] center = (width // 2, height // 2) # 通过仿射变换得到旋转矩阵 rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0) # 进行仿射变换 rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height)) # 创建旋转模糊核 kernel_size = int(strength) if kernel_size % 2 == 0: kernel_size += 1 # 确保核的大小是奇数 blur_kernel = np.ones((kernel_size, kernel_size), dtype=np.float32) / (kernel_size * kernel_size) # 应用旋转模糊 rotated_blurred_image = cv2.filter2D(rotated_image, -1, blur_kernel) # 保存结果 cv2.imwrite(output_path, rotated_blurred_image) # 示例调用 rotate_blur("input.jpg", "output.jpg", angle=45, strength=15)
请确保已经安装了OpenCV库,可以使用以下命令进行安装:
pip install opencv-python
在这个示例中,rotate_blur
函数接受输入图像的路径、输出路径、旋转角度和模糊强度作为参数。函数首先读取图像,然后通过仿射变换旋转图像,最后使用二维卷积来应用旋转模糊。最终的结果保存在指定的输出路径中。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
