python如何输出批量图片大小
时间: 2023-06-29 14:12:07 浏览: 92
你可以使用 Python 的 OpenCV 模块来输出批量图片的大小。下面是一个简单的示例代码:
```python
import cv2
import os
# 图片所在的文件夹路径
folder_path = "path/to/folder"
# 遍历文件夹中的所有图片
for filename in os.listdir(folder_path):
if filename.endswith(".jpg") or filename.endswith(".png"):
# 读取图片
img_path = os.path.join(folder_path, filename)
img = cv2.imread(img_path)
# 获取图片大小
height, width, channels = img.shape
print(f"{filename}: {width}x{height}")
```
在上面的代码中,我们首先指定了包含图片文件的文件夹路径 `folder_path`。然后,我们使用 `os.listdir` 函数遍历文件夹中的所有文件,并通过检查文件扩展名来过滤出图片文件。对于每个图片文件,我们使用 OpenCV 的 `cv2.imread` 函数读取图片,然后使用图片对象的 `shape` 属性获取其大小。最后,我们将文件名和大小输出到控制台。
相关问题
python 批量压缩图片大小
你可以使用Python中的Pillow库来批量压缩图片大小。
首先,你需要安装Pillow库。你可以使用以下命令来安装:
```
pip install Pillow
```
接下来,你可以使用以下代码来批量压缩图片大小:
```python
from PIL import Image
import os
def compress_images(directory=None, quality=30):
"""
压缩指定目录下的所有图片
:param directory: 图片所在的目录
:param quality: 压缩质量,默认为30
"""
if directory is None:
directory = os.getcwd()
print(f"压缩 {directory} 目录下的所有图片")
for filename in os.listdir(directory):
if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"):
filepath = os.path.join(directory, filename)
with Image.open(filepath) as im:
im.save(filepath, quality=quality)
print("完成压缩!")
# 示例
compress_images(directory="/path/to/directory", quality=50)
```
这个函数将遍历指定的目录,找到所有的 `.jpg`, `.jpeg`, 和 `.png` 文件,并将它们压缩到指定的质量级别。你可以根据需要调整 `quality` 参数的值来控制压缩质量。
请注意,这个函数将覆盖原始文件。如果你希望保留原始文件,请在保存压缩文件之前创建一个副本。
python批量修改图片大小
可以使用Pillow库来批量修改图片大小,具体操作可以参考以下代码:
```python
from PIL import Image
import os
# 设置图片路径和目标大小
path = 'image_folder/'
target_size = (500, 500)
# 遍历文件夹中的所有图片
for filename in os.listdir(path):
if filename.endswith('.jpg') or filename.endswith('.png'):
# 打开图片并修改大小
img = Image.open(os.path.join(path, filename))
img = img.resize(target_size)
# 保存修改后的图片
new_filename = os.path.splitext(filename)[0] + '_resized' + os.path.splitext(filename)[1]
img.save(os.path.join(path, new_filename))
```
这段代码会将`image_folder`文件夹中所有的`.jpg`和`.png`图片修改为大小为`(500, 500)`的图片,并在原文件名后加上`_resized`后缀保存。
阅读全文
相关推荐













