Python 降低分辨率
时间: 2023-11-05 07:18:06 浏览: 58
在Python中,有多种方法可以降低图像的分辨率。下面我将介绍两种常用的方法。
方法1: 使用PIL库
您可以使用Python Imaging Library(PIL)来降低图像的分辨率。以下是一个示例代码:
```
from PIL import Image
import os
def ResizeImage(filein, fileout, width, height):
allImage = os.listdir(filein)
for image in allImage:
img = Image.open(filein + "/" + image)
out = img.resize((width, height), Image.ANTIALIAS)
out.save(fileout + "/" + image)
# 使用示例
input_path = "输入图片文件夹路径"
output_path = "输出图片文件夹路径"
desired_width = 480
desired_height = 270
ResizeImage(input_path, output_path, desired_width, desired_height)
```
方法2: 使用FFmpeg库
如果您安装了FFmpeg,并且希望使用它来降低图像的分辨率,您可以使用以下代码:
```
import os
from ffmpy import FFmpeg
def change_size(input_path, output_dir, width, height):
allImage = os.listdir(input_path)
for image in allImage:
try:
image_path = input_path + "/" + image
ext = os.path.basename(image_path).strip().split('.')[-1]
if ext not in ['png', 'jpg']:
raise Exception('format error')
_result_path = os.path.join(output_dir, '{}.{}'.format(image[:-4], ext))
ff = FFmpeg(inputs={image_path: None}, outputs={_result_path: '-vf scale={}:{}'.format(width, height)})
ff.run()
except:
print(image + " 已转换")
# 使用示例
input_path = "输入图片文件夹路径"
output_dir = "输出图片文件夹路径"
desired_width = 480
desired_height = 270
change_size(input_path, output_dir, desired_width, desired_height)
```
您可以根据自己的需求选择其中一种方法来降低图像的分辨率。注意,在使用这些代码之前,您需要安装相关的库,并将输入和输出路径替换为您自己的路径。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [python程序改变图像的分辨率](https://blog.csdn.net/qq_43457119/article/details/124923148)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [python 降低图片分辨率的两种方法](https://blog.csdn.net/ChaoChao66666/article/details/124840576)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]