python 图片背景颜色识别

该博客介绍了如何使用Python进行图像处理,通过提取RGB颜色并转换为HSV来找到图像的主导颜色。文章中提供了一个函数,该函数忽略高亮度颜色并计算饱和度权重,从而确定主导颜色。最后,将RGB颜色转换为16进制格式,并给出了一个实际应用示例,处理了一张名为'blue.jpg'的图片。
摘要由CSDN通过智能技术生成
import colorsys
import PIL.Image as Image
 
# 函数生成的是RGB
# RGB转16进制 https://www.sioe.cn/yingyong/yanse-rgb-16/
def get_dominant_color(image):
    max_score = 0.0001
    dominant_color = None
    for count,(r,g,b) in image.getcolors(image.size[0]*image.size[1]):
        # 转为HSV标准
        saturation = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)[1]
        y = min(abs(r*2104+g*4130+b*802+4096+131072)>>13,235)
        y = (y-16.0)/(235-16)
        #忽略高亮色
        if y > 0.9:
            continue
        score = (saturation+0.1)*count
        if score > max_score:
            max_score = score
            dominant_color = (r,g,b)
    return dominant_color


# RGB转16进制函数
def RGB_to_Hex(tmp):
    rgb = tmp.split(',')#将RGB格式划分开来
    strs = '#'
    for i in rgb:
        num = int(i)#将str转int
        #将R、G、B分别转化为16进制拼接转换并大写
        strs += str(hex(num))[-2:].replace('x','0').upper()
    return strs

if __name__ == '__main__':
    image = Image.open('blue.jpg')
    image = image.convert('RGB')
    r=get_dominant_color(image)
    print(r)
    rgb_str=",".join([ str(x) for x in list(r)] )
    print(rgb_str)
    hexstr=RGB_to_Hex(rgb_str)
    print(hexstr)

效果还可以。先记录一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值