[RGB到python中的HSV转换

问题描述 投票:0回答:1

我想从头开始实现cv2.cvtColor(img,cv2.COLOR_BGR2HSV)背后的逻辑。我遵循了从下面给出的图片中选择的公式。但是,当我发现实现的功能与opencv函数之间的区别时,得到的输出却不是黑色图像,而是黑色图像。请帮助我了解我做错了什么。谢谢。

enter image description here

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) 

上面代码的输出如下。差异必须为零(黑色图像),但是我得到了不同的输出。

enter image description here

python image-processing opencv-python
1个回答
0
投票

您比较float32 V和float64 R,G,BV [i,j] == R [i,j]不正确H为零。更改您的代码:

  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)
© www.soinside.com 2019 - 2024. All rights reserved.