RGB到HSI的转换-色相总是计算为0

时间:2018-10-16 11:33:00

标签: python image numpy opencv

因此,我一直在尝试为我正在研究的项目创建这种RGB到HSI的转换算法,但是在执行过程中遇到了很多障碍。

到目前为止,我已将问题缩小为两个可能的问题:

  • 程序不会检测if语句中比较的两个值中的哪个为真,而仅默认为初始if语句
  • 程序在计算图像的色相时没有计算正确的值,因为它始终默认为反余弦的默认值。

代码如下:

import cv2
import numpy as np

def RGB_TO_HSI(img):

with np.errstate(divide='ignore', invalid='ignore'):

    bgr = cv2.split(img)

    intensity = np.divide(bgr[0] + bgr[1] + bgr[2], 3)
    saturation = 1 - 3 * np.divide(np.minimum(bgr[2], bgr[1], bgr[0]), bgr[2] + bgr[1] + bgr[0])

    def calc_hue(bgr):
        blue = bgr[0]
        green = bgr[1]
        sqrt_calc = np.sqrt(((bgr[2] - bgr[1]) * (bgr[2] - bgr[1])) + ((bgr[2] - bgr[0]) * (bgr[1] - bgr[0])))

        if green.any >= blue.any:
            hue = np.arccos(1/2 * ((bgr[2]-bgr[1]) + (bgr[2] - bgr[0])) / sqrt_calc)
        else:
            hue = 360 - np.arccos(1/2 * ((bgr[2]-bgr[1]) + (bgr[2] - bgr[0])) / sqrt_calc)

        hue = np.int8(hue)
        return hue

    hue = calc_hue(bgr)
    hsi = cv2.merge((intensity, saturation, calc_hue(bgr)))

Here is the formula I used for the conversion

提前感谢任何提示或想法

1 个答案:

答案 0 :(得分:0)

好的,这里发生了很多事情。我必须这样说,我知道您是新手,但是在发布问题之前,请检查文档,否则最终会错误地使用libs。 (即np.minimum()不能一次比较3个值)。

请注意您的变量类型。您的代码对np.uint8进行操作,就好像它们在np.int32处一样。始终尝试与变量类型保持一致。

足够了,在不更改太多代码的情况下,这就是我想到的:

import cv2
import numpy as np
from math import pi

def BGR_TO_HSI(img):

  with np.errstate(divide='ignore', invalid='ignore'):

    bgr = np.int32(cv2.split(img))

    blue = bgr[0]
    green = bgr[1]
    red = bgr[2]

    intensity = np.divide(blue + green + red, 3)

    minimum = np.minimum(np.minimum(red, green), blue)
    saturation = 1 - 3 * np.divide(minimum, red + green + blue)

    sqrt_calc = np.sqrt(((red - green) * (red - green)) + ((red - blue) * (green - blue)))

    if (green >= blue).any():
      hue = np.arccos((1/2 * ((red-green) + (red - blue)) / sqrt_calc))
    else:
      hue = 2*pi - np.arccos((1/2 * ((red-green) + (red - blue)) / sqrt_calc))

    hue = hue*180/pi

    hsi = cv2.merge((hue, saturation, intensity))
    return hsi

我希望它能帮助