把以上代码的输入图片修改为批量输入一个文件夹里的图片,并对文件所有图片各颜色总和占比计算
时间: 2023-09-20 11:10:02 浏览: 40
好的,针对您的需求,我可以为您提供以下代码示例:
```python
import os
from PIL import Image
# 定义函数,计算图片各颜色总和占比
def calculate_color_ratio(image):
# 获取图片像素点的 RGB 值
pixels = image.load()
width, height = image.size
total_pixels = width * height
# 初始化颜色总和
red_sum = 0
green_sum = 0
blue_sum = 0
# 遍历像素点,计算颜色总和
for x in range(width):
for y in range(height):
red_sum += pixels[x, y][0]
green_sum += pixels[x, y][1]
blue_sum += pixels[x, y][2]
# 计算颜色总和占比
red_ratio = red_sum / (total_pixels * 255)
green_ratio = green_sum / (total_pixels * 255)
blue_ratio = blue_sum / (total_pixels * 255)
# 返回颜色总和占比
return red_ratio, green_ratio, blue_ratio
# 定义函数,统计文件夹内所有图片的颜色总和占比
def calculate_folder_color_ratio(folder_path):
# 获取文件夹内所有图片路径
image_paths = [os.path.join(folder_path, file) for file in os.listdir(folder_path) if file.endswith(('jpg', 'jpeg', 'png', 'bmp'))]
# 初始化颜色总和
red_sum = 0
green_sum = 0
blue_sum = 0
# 遍历图片,计算颜色总和
for image_path in image_paths:
# 打开图片
image = Image.open(image_path)
# 计算颜色总和
red_ratio, green_ratio, blue_ratio = calculate_color_ratio(image)
red_sum += red_ratio
green_sum += green_ratio
blue_sum += blue_ratio
# 计算颜色总和占比
total_images = len(image_paths)
red_ratio = red_sum / total_images
green_ratio = green_sum / total_images
blue_ratio = blue_sum / total_images
# 返回颜色总和占比
return red_ratio, green_ratio, blue_ratio
# 测试函数
folder_path = './images'
red_ratio, green_ratio, blue_ratio = calculate_folder_color_ratio(folder_path)
print('Red ratio:', red_ratio)
print('Green ratio:', green_ratio)
print('Blue ratio:', blue_ratio)
```
以上代码中,`calculate_color_ratio()` 函数用于计算单张图片的颜色总和占比,`calculate_folder_color_ratio()` 函数用于统计文件夹内所有图片的颜色总和占比。您只需要将代码中的 `folder_path` 参数修改为您存放图片的文件夹路径即可。
希望对您有所帮助!