python图像批量降采样
时间: 2023-07-11 22:35:38 浏览: 130
可以使用Pillow库来实现Python图像的批量降采样。以下是一个示例代码:
```python
from PIL import Image
import os
input_folder = 'input_folder_path'
output_folder = 'output_folder_path'
size = (500, 500) # 降采样后的大小
for filename in os.listdir(input_folder):
if filename.endswith('.jpg') or filename.endswith('.png'): # 只处理jpg和png格式的文件
image = Image.open(os.path.join(input_folder, filename))
image.thumbnail(size) # 降采样
image.save(os.path.join(output_folder, filename))
```
在这个示例中,我们首先指定了输入和输出文件夹的路径,以及降采样后的大小。然后,我们遍历输入文件夹中的所有文件,仅处理jpg和png格式的文件。对于每个文件,我们使用Pillow库中的`Image.open()`函数打开它,然后使用`thumbnail()`函数降采样。最后,我们使用`save()`函数将降采样后的图像保存到输出文件夹中。
相关问题
python图像降采样
Python中可以使用Pillow库来进行图像降采样。
首先,导入Pillow库:
```python
from PIL import Image
```
然后,使用open()方法打开图像文件:
```python
img = Image.open('image.jpg')
```
使用resize()方法进行降采样,指定新的图像大小:
```python
new_size = (img.width//2, img.height//2)
resized_img = img.resize(new_size)
```
最后,保存降采样后的图像:
```python
resized_img.save('resized_image.jpg')
```
完整代码如下:
```python
from PIL import Image
img = Image.open('image.jpg')
new_size = (img.width//2, img.height//2)
resized_img = img.resize(new_size)
resized_img.save('resized_image.jpg')
```
python图片降采样
Python图片降采样是一种减少图片分辨率的操作,即通过减少像素数量达到降低图片分辨率并减小图片文件大小的目的。
要完成图片降采样的操作,可以使用Python的Pillow库。使用Pillow库的resize()方法来改变图片分辨率。具体步骤如下:
1. 读取图片:使用Pillow库中的Image.open()方法读取原始图片。
2. 设置降采样后的图片大小:根据需求设置图片降采样后的大小。
3. 执行图片降采样操作:使用resize()方法对图片进行降采样处理并保存图片。
比如,以下代码将读取名为"example.jpg"的图片,将其降采样为100 x 100像素的大小并保存到名为"example_resized.jpg"的文件中。
```
from PIL import Image
# 读取原始图片
img = Image.open('example.jpg')
# 设置降采样后的图片大小
size = (100, 100)
# 执行图片降采样操作并保存图片
resized_img = img.resize(size)
resized_img.save('example_resized.jpg')
```
需要注意的是,使用该方法进行降采样的过程中,会导致图片细节变模糊,因此需要在使用之前和之后仔细观察降采样前后的差异以确保操作达到预期效果。