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的颜色值进行排序,并输出其颜色和占比。

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值