python批量处理图片尺寸,比如256*256到128*128

可以使用Python中的Pillow库来完成这个任务。以下是一个简单的代码示例,它将一个文件夹中的所有256x256像素的图片缩小为128x128像素并保存到另一个文件夹中。

from PIL import Image
import os

input_folder = '/path/to/input/folder'
output_folder = '/path/to/output/folder'
new_size = (128, 128)

# Loop through all the files in the input folder
for filename in os.listdir(input_folder):
    # Check if the file is an image
    if filename.endswith('.png') or filename.endswith('.jpg'):
        # Open the image and resize it
        img = Image.open(os.path.join(input_folder, filename))
        img = img.resize(new_size)

        # Save the resized image to the output folder
        new_filename = os.path.splitext(filename)[0] + '_resized.png'
        img.save(os.path.join(output_folder, new_filename))

在这个例子中:

input_folder 是包含要缩小的图片的文件夹路径

output_folder 是将缩小的图片保存到的文件夹路径

new_size 是缩小后的图片尺寸

代码会检查每个文件是否是图片,如果是,就打开它、缩小它、并将其保存到输出文件夹中。

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要导入OpenCV库: ```python import cv2 ``` 然后,我们可以使用`cv2.imread()`函数读取一张图片: ```python img = cv2.imread('image.jpg') ``` 接下来,我们可以使用`cv2.resize()`函数来进行图像分辨率的升采样和降采样。其中,`cv2.resize()`函数的第一个参数是原始图片,第二个参数是目标图片的大小(可以是宽度和高度的元组或者一个缩放比例因子),第三个参数是插值方法。 例如,我们可以将一张图片的分辨率降低一半: ```python resized_img = cv2.resize(img, (img.shape[1]//2, img.shape[0]//2), interpolation = cv2.INTER_AREA) ``` 或者将一张图片的分辨率提高一倍: ```python resized_img = cv2.resize(img, (img.shape[1]*2, img.shape[0]*2), interpolation = cv2.INTER_CUBIC) ``` 其中,`cv2.INTER_AREA`表示使用平均像素值进行降采样,`cv2.INTER_CUBIC`表示使用三次样条插值进行升采样。 最后,我们可以使用`cv2.imshow()`函数来显示结果: ```python cv2.imshow('Original Image', img) cv2.imshow('Resized Image', resized_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 完整代码如下: ```python import cv2 img = cv2.imread('image.jpg') resized_img = cv2.resize(img, (img.shape[1]//2, img.shape[0]//2), interpolation = cv2.INTER_AREA) #resized_img = cv2.resize(img, (img.shape[1]*2, img.shape[0]*2), interpolation = cv2.INTER_CUBIC) cv2.imshow('Original Image', img) cv2.imshow('Resized Image', resized_img) cv2.waitKey(0) cv2.destroyAllWindows() ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值