简体   繁体   中英

RGB to HSV conversion in python

I would like to implement the logic behind cv2.cvtColor(img,cv2.COLOR_BGR2HSV) from scratch. 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. Please help me understand what have i done wrong. Thank you.

在此处输入图像描述

The implementation of BGR2HSV Conversion.

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. The difference has to be a zero (black image) but i got different output.

在此处输入图像描述

You compare float32 V and float64 R,G,BV[i,j] == R[i,j] It is incorrect. H is zero. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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