你可以使用ColorThief来获取多个图像的主要颜色吗?

huangapple go评论63阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月10日 04:19:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定