python计算图片中各颜色占比

如题,图片也比较简单,目前还没实现,其他人发的都看了,不太行,有没有靠谱的…


from PIL import Image  
import numpy as np  
import collections  
  
def get_color_counts(image_path):  
    # 读取图片  
    img = Image.open(image_path)  
    img_data = np.array(img)  
  
    # 获取图像的宽度和高度  
    width, height, _ = img_data.shape  
  
    # 将RGB值转化为整数,方便统计  
    img_data = img_data.view(collections.Counter)  
  
    # 计算颜色比例  
    color_counts = {}  
    for (color, count) in img_data.items():  
        color_counts[color] = count / (width * height)  
  
    return color_counts  
  
image_path = 'your_image_path.jpg'  # 替换为你的图片路径  
color_counts = get_color_counts(image_path)  
print(color_counts)

【以下回答由 GPT 生成】

答案:

你可以使用Python中的PIL库来处理图片,并使用numpy库来进行数组计算。以下是一个实现计算图片中各个颜色占比的具体步骤:

  1. 首先,确保你已经安装了PIL库和numpy库。你可以使用以下命令来安装它们:
pip install pillow
pip install numpy
  1. 使用PIL库的open()函数来打开图片文件,并将其加载为一个PIL.Image对象:
from PIL import Image

image = Image.open("your_image.jpg")
  1. 将PIL.Image对象转换为numpy数组。这可以通过numpy.array()函数来实现:
import numpy as np

image_array = np.array(image)
  1. 将图像数组的维度重新排列,使其变为两个维度:高度和宽度,并转换为浮点类型:
image_array = np.reshape(image_array, (-1, 3)).astype(float)
  1. 使用numpy库的unique函数来获取图片中所有颜色的列表:
unique_colors = np.unique(image_array, axis=0)
  1. 创建一个字典来存储每个颜色的像素数量:
color_counts = {}
  1. 遍历图片数组,并统计每种颜色的像素数量:
for color in unique_colors:
    count = np.sum(np.all(image_array == color, axis=1))
    color_counts[tuple(color)] = count
  1. 计算每种颜色的占比:
total_pixels = image_array.shape[0]
color_ratios = {color: count/total_pixels for color, count in color_counts.items()}
  1. 完整的代码示例:
from PIL import Image
import numpy as np

def calculate_color_ratios(image_path):
    image = Image.open(image_path)
    image_array = np.array(image)
    image_array = np.reshape(image_array, (-1, 3)).astype(float)

    unique_colors = np.unique(image_array, axis=0)
    color_counts = {}

    for color in unique_colors:
        count = np.sum(np.all(image_array == color, axis=1))
        color_counts[tuple(color)] = count

    total_pixels = image_array.shape[0]
    color_ratios = {color: count/total_pixels for color, count in color_counts.items()}

    return color_ratios

color_ratios = calculate_color_ratios("your_image.jpg")
print(color_ratios)

请将上述代码中的"your_image.jpg"替换为你要计算的图片路径。代码会输出一个字典,其中键是颜色的RGB值,值是该颜色的占比。

如果你想要计算不同颜色的占比,并将结果可视化,你可以使用matplotlib库来绘制直方图。具体的步骤可以参考以下示例代码:

import matplotlib.pyplot as plt

def plot_color_ratios(color_ratios):
    colors = list(color_ratios.keys())
    ratios = list(color_ratios.values())

    plt.figure(figsize=(8, 6))
    plt.bar(range(len(colors)), ratios, color=colors)
    plt.xticks(range(len(colors)), colors)
    plt.xlabel('Color')
    plt.ylabel('Ratio')
    plt.title('Color Ratios')

    plt.show()

plot_color_ratios(color_ratios)

希望以上解决方案对你有所帮助,如果你还有任何问题,请随时提问。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

你丫的描述都不明确,问题都不靠谱,问个毛线呀。你这颜色的维度是什么?