获取文件夹中的随机100张图片,如果不足100张则获取全部
时间: 2025-06-15 14:19:48 浏览: 13
要在Python中获取文件夹中的随机100张图片,首先需要导入必要的库如`os`, `shutil` 和 `random`。假设图片都在一个名为"images"的文件夹下,并且它们都是JPEG、PNG等常见的图片格式,你可以按照以下步骤操作:
1. 导入所需的库:
```python
import os
import shutil
import random
from PIL import Image
```
2. 定义图片路径和目标数量(这里设定为100张):
```python
image_folder = "images"
target_images = 100
```
3. 创建一个函数来获取随机图片列表:
```python
def get_random_images(num_needed):
images = []
for filename in os.listdir(image_folder):
if filename.endswith(('.jpg', '.jpeg', '.png', '.gif')):
img_path = os.path.join(image_folder, filename)
with Image.open(img_path) as im:
# 检查图片是否适合(例如尺寸大小)
if some_condition(im): # 添加条件判断
images.append(img_path)
return random.sample(images, min(len(images), num_needed))
```
4. 如果图片总数少于100张,获取所有图片;否则,取随机100张:
```python
all_images = get_random_images(target_images)
if len(all_images) < target_images:
print(f"文件夹内只有 {len(all_images)} 张图片,将获取全部")
else:
print(f"已随机选取 {target_images} 张图片")
# 现在可以处理这100张图片,例如保存到另一个文件夹或进行其他操作
for image in all_images[:target_images]: # 取前100张
shutil.copy(image, "output_folder") # 示例:复制图片到新文件夹
```
在这个例子中,你需要根据实际情况替换`some_condition()`,比如检查图片的分辨率、大小或其他限制条件。
阅读全文
相关推荐


















