简体   繁体   English

python 中的 RGB 到 HSV 转换

[英]RGB to HSV conversion in python

I would like to implement the logic behind cv2.cvtColor(img,cv2.COLOR_BGR2HSV) from scratch.我想从头开始实现cv2.cvtColor(img,cv2.COLOR_BGR2HSV)背后的逻辑。 I have followed the formulas picked from the picture given below.我遵循了从下面给出的图片中挑选的公式。 However, when i find out the difference between the function i implemented and the opencv function, instead of getting a black image, i got different output. However, when i find out the difference between the function i implemented and the opencv function, instead of getting a black image, i got different output. Please help me understand what have i done wrong.请帮助我了解我做错了什么。 Thank you.谢谢你。

在此处输入图像描述

The implementation of BGR2HSV Conversion. BGR2HSV转换的实现。

def convertBGRtoHSV(image):
###
### YOUR CODE HERE
###
  sample = (image * (1/255.0))
  B,G,R = cv2.split(sample)

  rows,cols,channels = sample.shape

  V = np.zeros(sample.shape[:2],dtype=np.float32)
  S = np.zeros(sample.shape[:2],dtype=np.float32)
  H = np.zeros(sample.shape[:2],dtype=np.float32)



  for i in range(rows):
      for j in range(cols):
          V[i,j] = max(B[i,j],G[i,j],R[i,j])
          Min_RGB = min(B[i,j],G[i,j],R[i,j])


          if V[i,j] != 0.0:
              S[i,j] = ((V[i,j] - Min_RGB) / V[i,j])
          else:
              S[i,j] = 0.0

          if V[i,j] == R[i,j]:
              H[i,j] = 60*(G[i,j] - B[i,j])/(V[i,j] - Min_RGB)
          elif V[i,j] == G[i,j]:
              H[i,j] = 120 + 60*(B[i,j] - R[i,j])/(V[i,j] - Min_RGB)
          elif V[i,j] == B[i,j]:
              H[i,j] = 240 + 60*(R[i,j] - G[i,j])/(V[i,j] - Min_RGB)

          if H[i,j] < 0:
              H[i,j] = H[i,j] + 360


  V = 255.0 * V
  S = 255.0 * S
  H = H/2
  hsv = np.round(cv2.merge((H,S,V)))
  return hsv.astype(np.int) 

The output of the above code is given below.下面给出上述代码的output。 The difference has to be a zero (black image) but i got different output.差异必须为零(黑色图像),但我得到不同的 output。

在此处输入图像描述

You compare float32 V and float64 R,G,BV[i,j] == R[i,j] It is incorrect.你比较 float32 V 和 float64 R,G,BV[i,j] == R[i,j] 是不正确的。 H is zero. H 为零。 Change you code:更改您的代码:

  V = np.zeros(sample.shape[:2],dtype=np.float64)
  S = np.zeros(sample.shape[:2],dtype=np.float64)
  H = np.zeros(sample.shape[:2],dtype=np.float64)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM