簡體   English   中英

python 中的 RGB 到 HSV 轉換

[英]RGB to HSV conversion in python

我想從頭開始實現cv2.cvtColor(img,cv2.COLOR_BGR2HSV)背后的邏輯。 我遵循了從下面給出的圖片中挑選的公式。 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. 請幫助我了解我做錯了什么。 謝謝你。

在此處輸入圖像描述

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) 

下面給出上述代碼的output。 差異必須為零(黑色圖像),但我得到不同的 output。

在此處輸入圖像描述

你比較 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM