英文:
How can I use ColorThief to obtain the dominant color of multiple images?
问题
我在桌面上有一个包含大约1,000张图片的文件夹,我希望使用Python中的ColorThief来获取每张图片的主要颜色(以RGB格式)。我找到了以下代码,但显然这只适用于一次处理一张图片。
color_thief = ColorThief('/path/to/file')
dominant_color = color_thief.get_color(quality=1)
print(dominant_color)
有没有办法一次处理整个图片批量?我希望将文件名作为一列,RGB值作为另一列。
当前的代码只能一次处理一张图片。
英文:
I have a folder on my desktop of about 1,000 images and I'm hoping to use ColorThief in Python to obtain the dominant color (in RGB format) for each one. I found the following code, but this obviously only works for one image at a time.
color_thief = ColorThief('/path/to/file')
dominant_color = color_thief.get_color(quality=1)
print(dominant_color)
Is there a way to do the whole batch of images at once? I am hoping to get the file name as one column and the RGB value as the other.
Only able to use one image at a time with current code.
答案1
得分: 1
你可以使用os.listdir()
来获取目录中的所有图片:
import os
from colorthief import ColorThief
image_path = '/path/to';
images = [image for image in os.listdir(image_path)] # 假设路径中只包含图片
dominant_colors = {}
for image in images:
color_thief = ColorThief(os.path.join(image_path, image))
dominant_colors.update({(image, color_thief.get_color(quality=1))})
for image, dominant_color in dominant_colors.items():
print(image, dominant_color)
英文:
You can use os.listdir()
to get all the images in your directory:
import os
from colorthief import ColorThief
image_path = '/path/to'
images = [image for image in os.listdir(image_path)] # assuming only images are in the path
dominant_colors = {}
for image in images:
color_thief = ColorThief(os.path.join(image_path, image))
dominant_colors.update({(image, color_thief.get_color(quality=1))})
for image, dominant_color in dominant_colors.items():
print(image, dominant_color)
I saved the dominant colors in a dictionary so when printing you get the image name with the corresponding dominant color.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论