在Python中手动将RGB转换为HSI

2024-10-01 09:21:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个任务要交,需要一些帮助。在

所以,我需要把RGB从一个图像转换成HSI并打印出三个图像(1。色调,2。饱和度和3。强度)。在

我不能使用openCV之外的任何库来加载和打印图像;其他任何操作都必须手动完成。在

我认为计算是对的,但我似乎无法正确地打印出来。我告诉我不能,因为输入是元组而输出不是元组。所以,我的输出(放置像素)现在是空的。在

希望有人能帮忙!!在

import math
from PIL import Image

RgbString = ' :RGB for pixel: '
HsiString = ' :HSI for pixel: '

img = Image.open('MemeFace.jpg')
HImage = Image.new("HSV", (img.width, 
img.height))
rgb_img = img.convert('RGB')
r, g, b = rgb_img.getpixel((1, 1))
HImage.convert('HSV')


def rgb2hsv(r, g, b):
    r = float(r)
    g = float(g)
    b = float(b)
    high = max(r, g, b)
    low = min(r, g, b)
    h, s, v = high, high, high

    d = high - low
    s = 0 if high == 0 else d/high

    if high == low:
        h = 0.0
    else:
        h = {
            r: (g - b) / d + (6 if g < b 
    else 0),
            g: (b - r) / d + 2,
            b: (r - g) / d + 4,
        }[high]
        h /= 6

    return h,s,v



for x in range (1, img.width):
    for y in range (1, img.height):
        r, g, b = rgb_img.getpixel((x,y))

        print(r, g, b, RgbString,  x, y)
        print(rgb2hsv(r, g, b), 
        HsiString, x, y)


        HImage.putpixel((x, y), ())


Image._show(HImage)

Image.fromdef

Tags: 图像imageimportimgforifrgbfloat