python图片:获得颜色占比,图片尺寸

꧂ 获得颜色占比,图片尺寸꧁

要获取图片的尺寸、大小和颜色占比大于0.001的颜色值,可以基于上一个回答中使用Pillow库的代码进行修改。

from PIL import Image

# 输入图片路径
image_path = input("请输入图片路径: ")

try:
    # 打开图片文件
    image = Image.open(image_path)

    # 获取图片尺寸
    width, height = image.size
    print("图片尺寸:{}x{}".format(width, height))

    # 获取图片大小
    size = image.size[0] * image.size[1]
    print("图片大小:{} 字节".format(size))

    # 统计图片颜色占比
    pixels = image.getdata()
    color_count = {}
    total_pixels = 0

    for pixel in pixels:
        total_pixels += 1
        color_count[pixel] = color_count.get(pixel, 0) + 1

    color_percentage = {color: count / total_pixels for color, count in color_count.items() if count / total_pixels > 0.001}

    print("颜色占比(占比大于 0.001):")
    for color, percentage in color_percentage.items():
        print("颜色 {} 占比:{:.2f}%".format(color, percentage * 100))

except IOError:
    print("无法打开图片文件,请检查路径是否正确。")
except Exception as e:
    print("发生错误:", str(e))

运行代码后,程序会要求您输入图片路径。

输入正确的图片路径后,程序将会打印出图片的尺寸、大小和颜色占比大于0.001的颜色值及其占比。

请注意,颜色占比的阈值可以根据您的需求进行修改,只需将代码中的0.001改为其他比例即可。

꧂按照图片颜色占比大小进行排序꧁

要按照图片颜色占比大小进行排序,可以使用Python的sorted()函数,并根据字典中的值进行排序。

在上面的代码基础上进行修改,添加对颜色占比的排序功能:

from PIL import Image

# 输入图片路径
image_path = input("请输入图片路径: ")

try:
    # 打开图片文件
    image = Image.open(image_path)

    # 获取图片尺寸
    width, height = image.size
    print("图片尺寸:{}x{}".format(width, height))

    # 获取图片大小
    size = image.size[0] * image.size[1]
    print("图片大小:{} 字节".format(size))

    # 统计图片颜色占比
    pixels = image.getdata()
    color_count = {}
    total_pixels = 0

    for pixel in pixels:
        total_pixels += 1
        color_count[pixel] = color_count.get(pixel, 0) + 1

    color_percentage = {color: count / total_pixels for color, count in color_count.items() if count / total_pixels > 0.001}

    print("颜色占比(占比大于 0.001):")
    sorted_colors = sorted(color_percentage.items(), key=lambda x: x[1], reverse=True)
    for color, percentage in sorted_colors:
        print("颜色 {} 占比:{:.2f}%".format(color, percentage * 100))

except IOError:
    print("无法打开图片文件,请检查路径是否正确。")
except Exception as e:
    print("发生错误:", str(e))
输入图片路径后,程序将会打印出图片的尺寸、大小,并对颜色占比大于0.001的颜色值进行排序,并输出其颜色和占比。

python图片:获得颜色占比,图片尺寸_第1张图片
python图片:获得颜色占比,图片尺寸_第2张图片

你可能感兴趣的:(python,青少年编程,自动化,图像处理,数据库)