当前位置:首页>python>手把手教你用Python打造一个简单的图像处理工具

手把手教你用Python打造一个简单的图像处理工具

  • 2026-10-10 12:12:23
手把手教你用Python打造一个简单的图像处理工具

你是否曾经想过,只需几行Python代码就能实现像Photoshop一样的图像缩放和滤镜效果?今天,我们就来一起动手,用Python打造一个简单而实用的图像处理工具。

准备工作:安装必要的库

我们主要用到两个强大的图像处理库:

  • Pillow:Python最基础、最易用的图像处理库,适合日常的裁剪、缩放、滤镜等操作

  • OpenCV:功能更强大的计算机视觉库,适合更复杂的图像处理任务

安装命令非常简单:

pip install pillow opencv-python numpy

小贴士:如果只想做简单的图像处理,只安装Pillow就足够了。

一、图像缩放功能

图像缩放是最常用的图像处理操作之一。我们来看看如何使用Pillow实现。

1. 缩放到指定尺寸

from PIL import Image# 打开图像img = Image.open('input.jpg')# 缩放到800x600像素resized_img = img.resize((800, 600))resized_img.save('resized_output.jpg')

代码很简单,resize()方法接收一个元组(宽度, 高度)作为参数。

2. 按比例缩放(保持宽高比)

如果不想让图片变形,可以按比例缩放:

from PIL import Imagedef resize_with_ratio(input_path, output_path, target_width):    img = Image.open(input_path)    # 计算等比例高度    ratio = target_width / img.width    target_height = int(img.height * ratio)    # 缩放    resized = img.resize((target_width, target_height))    resized.save(output_path)resize_with_ratio('input.jpg', 'output.jpg', 400)

这样就能保证图片不会变形啦!

3. 缩放到原来的一半

from PIL import Imageimg = Image.open('input.jpg')# 宽高各取一半new_size = (img.width // 2, img.height // 2)half_img = img.resize(new_size)half_img.save('half_output.jpg')

4. 使用OpenCV缩放

OpenCV也提供了缩放功能:

import cv2img = cv2.imread('input.jpg')# 缩放到指定尺寸resized = cv2.resize(img, (800, 600))cv2.imwrite('opencv_output.jpg', resized)

二、滤镜应用

滤镜是让照片秒变"大片"的神器。我们来看看几种常见的滤镜效果。

1. 黑白滤镜(灰度图)

把彩色照片变成黑白老照片的感觉:

from PIL import Imageimg = Image.open('input.jpg')gray_img = img.convert('L')  # 'L'代表灰度模式gray_img.save('gray_output.jpg')
使用OpenCV实现:
import cv2img = cv2.imread('input.jpg')gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)cv2.imwrite('gray_output.jpg', gray)

2. 模糊滤镜

让照片变得柔和朦胧:

from PIL import Image, ImageFilterimg = Image.open('input.jpg')# 普通模糊blurred = img.filter(ImageFilter.BLUR)blurred.save('blur_output.jpg')# 高斯模糊(更自然)gaussian = img.filter(ImageFilter.GaussianBlur(radius=2))gaussian.save('gaussian_output.jpg')

3. 浮雕滤镜

让照片呈现出雕刻般的立体感:

from PIL import Image, ImageFilterimg = Image.open('input.jpg')embossed = img.filter(ImageFilter.EMBOSS)embossed.save('emboss_output.jpg')

4. 轮廓检测滤镜

提取图像的边缘轮廓,非常有艺术感:

from PIL import Image, ImageFilterimg = Image.open('input.jpg')contour = img.filter(ImageFilter.CONTOUR)contour.save('contour_output.jpg')

5. 锐化滤镜

让照片更清晰、细节更突出:

from PIL import Image, ImageFilterimg = Image.open('input.jpg')sharpened = img.filter(ImageFilter.SHARPEN)sharpened.save('sharp_output.jpg')

6. 复古滤镜(棕褐色调)

用OpenCV实现更有胶片感的复古效果:

import cv2import numpy as npdef sepia_filter(input_path, output_path):    img = cv2.imread(input_path)    # 复古变换矩阵    kernel = np.array([        [0.393, 0.769, 0.189],        [0.349, 0.686, 0.168],        [0.272, 0.534, 0.131]    ])    sepia = cv2.transform(img, kernel)    # 限制像素值在0-255之间    sepia = np.clip(sepia, 0, 255).astype(np.uint8)    cv2.imwrite(output_path, sepia)sepia_filter('input.jpg', 'sepia_output.jpg')

三、组合成一个完整的图像处理工具

把上面这些功能整合到一起,做成一个简单的命令行工具:

from PIL import Image, ImageFilterimport argparseimport osdef process_image(input_path, output_path, operation, **kwargs):    img = Image.open(input_path)    if operation == 'resize':        width = kwargs.get('width', img.width)        height = kwargs.get('height', img.height)        img = img.resize((width, height))    elif operation == 'resize_ratio':        target_width = kwargs.get('width', 400)        ratio = target_width / img.width        target_height = int(img.height * ratio)        img = img.resize((target_width, target_height))    elif operation == 'gray':        img = img.convert('L')    elif operation == 'blur':        img = img.filter(ImageFilter.BLUR)    elif operation == 'gaussian':        radius = kwargs.get('radius', 2)        img = img.filter(ImageFilter.GaussianBlur(radius=radius))    elif operation == 'emboss':        img = img.filter(ImageFilter.EMBOSS)    elif operation == 'contour':        img = img.filter(ImageFilter.CONTOUR)    elif operation == 'sharpen':        img = img.filter(ImageFilter.SHARPEN)    img.save(output_path)    print(f'✅ 处理完成!保存至:{output_path}')# 命令行入口if __name__ == '__main__':    parser = argparse.ArgumentParser(description='Python图像处理小工具')    parser.add_argument('input', help='输入图片路径')    parser.add_argument('-o', '--output', help='输出图片路径', default='output.jpg')    parser.add_argument('-op', '--operation',                         choices=['resize', 'resize_ratio', 'gray', 'blur',                                 'gaussian', 'emboss', 'contour', 'sharpen'],                        required=True, help='操作类型')    parser.add_argument('-w', '--width', type=int, help='目标宽度')    parser.add_argument('-h', '--height', type=int, help='目标高度')    parser.add_argument('-r', '--radius', type=float, default=2, help='高斯模糊半径')    args = parser.parse_args()    process_image(args.input, args.output, args.operation,                  width=args.width, height=args.height, radius=args.radius)
使用方式:
# 缩放图片到指定尺寸python image_tool.py input.jpg -op resize -w 800 -h 600 -o output.jpg# 等比例缩放python image_tool.py input.jpg -op resize_ratio -w 400 -o output.jpg# 转黑白python image_tool.py input.jpg -op gray -o gray.jpg# 高斯模糊python image_tool.py input.jpg -op gaussian -r 3 -o blur.jpg# 浮雕效果python image_tool.py input.jpg -op emboss -o emboss.jpg

进阶:打造带界面的图像处理工具

如果你想让工具更直观好用,可以结合 PyQt5 或 Tkinter 做一个图形化界面。这样用户可以通过鼠标拖拽、滑块调节等方式来操作图片,体验会更好。

总结

今天我们学习了:

  1. 图像缩放:使用resize()方法可以轻松调整图片尺寸

  2. 多种滤镜效果:灰度、模糊、浮雕、轮廓检测、锐化、复古等

  3. 整合成完整工具:把零散功能组合成一个命令行工具

整个过程只需要几十行Python代码,是不是很简单?Pillow适合快速开发原型,OpenCV则适合更复杂的图像处理任务。你可以根据自己的需求选择合适的库,甚至把它们结合起来使用。

赶快动手试试吧!用Python给自己的照片添加炫酷的滤镜效果,成就感满满!🎉

最新文章

随机文章