美文网首页
python rgb2hsv hsltorgb

python rgb2hsv hsltorgb

作者: 承诺一时的华丽 | 来源:发表于2021-07-01 14:29 被阅读0次
    def rgb2hsv(self, r, g, b):
        r = r / 255
        g = g / 255
        b = b / 255

        mi = min(r, g, b)
        ma = max(r, g, b)
        l = (mi + ma) / 2
        difference = ma - mi
        if ma == mi:
            h = 0
            s = 0
        else:
            s = difference / (2.0 - ma - mi) if l > 0.5 else difference / (ma +
                                                                           mi)

            if ma == r:
                h = ((g - b) / difference) + (6 if g < b else 0)
            elif ma == g:
                h = 2.0 + (b - r) / difference
            elif ma == b:
                h = 4.0 + (r - g) / difference

            h = round(h * 60)

        s = round(s * 100)
        l = round(l * 100)
        return h, s, l

    def hsltorgb(self, h, s, l):
        h = h / 360
        s = s / 100
        l = l / 100
        rgb = [0, 1, 2]

        if s == 0:
            rgb = [round(l * 255), round(l * 255), round(l * 255)]
        else:
            q = (l + s - l * s) if l >= 0.5 else (l * (1 + s))
            p = 2 * l - q

            rgb[0] = h + 1 / 3
            rgb[1] = h
            rgb[2] = h - 1 / 3
            for i in range(3):
                tc = rgb[i]
                if tc < 0:
                    tc = tc + 1
                elif tc > 1:
                    tc = tc - 1

                if tc < (1 / 6):
                    tc = p + (q - p) * 6 * tc
                elif ((1 / 6) <= tc and tc < 0.5):
                    tc = q
                elif (0.5 <= tc and tc < (2 / 3)):
                    tc = p + (q - p) * (4 - 6 * tc)
                else:
                    tc = p

                rgb[i] = round(tc * 255)

        return rgb

相关文章

网友评论

      本文标题:python rgb2hsv hsltorgb

      本文链接:https://www.haomeiwen.com/subject/pamjultx.html