python - RGB 到 HSI 转换 - 色调始终计算为 0

标签 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

提前感谢任何提示或想法

最佳答案

好的,这里发生了很多事情。我必须这样说,我知道你是新手,但在你发布问题之前检查文档,否则你最终会错误地使用库。 (即 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

希望对你有帮助

关于python - RGB 到 HSI 转换 - 色调始终计算为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52834537/

相关文章:

python - 为什么 ffmpeg-python 的输出与图像形状不匹配?

javascript - 在客户端将图像从 html 转换为 jpg (javascript)

python - 选择 3d ndarray 中的第一列

python - NumPy:3 字节、6 字节类型(又名 uint24、uint48)

python - 使用 Flask、SQLAlchemy 和 WTForms 更新多对多关系?

python - Django,更改用户名

python - python中的并行API请求

image - 如何使用 OpenCV 去除图像的背景?

html - 相对于图像定位文本

python - 将分类变量放入多列 (2)