首页 > 解决方案 > 在 Python 中手动将 RGB 转换为 HSI

问题描述

我有一个作业到期,需要一些帮助。

因此,我需要将 RGB 从图像转换为 HSI 并打印出三幅图像(1. 色调、2. 饱和度和 3. 强度)。

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

我(我认为)计算正确,但我似乎无法正确打印。我告诉我我不能,因为输入是一个元组而输出不是。所以,我的输出(put.pixel)现在是空的。

希望任何人都可以提供帮助!

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

标签: pythonimagergbhsvconverters

解决方案


推荐阅读