【画像処理100本ノック】Q.5. RGB⇔HSV変換

参考になったサイト

https://www.peko-step.com/tool/hsvrgb.html

RGB➡HSV 

def RGB2HSV(img):
  img = img.astype(np.float32)
  b = img[:, :, 0].copy() 
  g = img[:, :, 1].copy() 
  r = img[:, :, 2].copy() 
  H = img[:, :, 0].copy()
  V = H.copy()
  S = H.copy()
  tate = b.shape[1]#縦の画素数
  yoko = b.shape[0]#横の画素数

  for i in range(tate):
    for j in range(yoko):
      Max = max(b[i][j], g[i][j], r[i][j] )
      Min = min(b[i][j], g[i][j], r[i][j] )
  
      if Max == Min:
        H[i][j] = 0
      elif Max == b[i][j]:
        H[i][j] = 60 * (r[i][j] - g[i][j]) // (Max - Min) + 240
      elif Max == r[i][j]:
        H[i][j] = 60 * (g[i][j] - b[i][j]) // (Max - Min)
      elif Max == g[i][j]:
        H[i][j] = 60 * (b[i][j] - r[i][j]) // (Max - Min) + 120
      
      if H[i][j] <0:
        H[i][j] = H[i][j] + 360      

      V[i][j] = Max
      S[i][j] = round(255 * (Max - Min) / Max, 0)

  return [H, S, V]

HSV➡RGB

def HSV2RGB(H,S,V,img,add):
  img = img.astype(np.float32)
  tate = np.shape(V)[1]#縦の画素数
  yoko = np.shape(V)[0]#横の画素数

  H_add = H + add
  for k in range(tate):
    for l in range(yoko):
      if H_add[k][l] > 360:
        H_add[k][l] = H_add[k][l] - 360
  Max = V.copy()
  Min = V.copy()
  H_ = H_add / 60

  b = V.copy()
  g = V.copy()
  r = V.copy()

  for i in range(tate):
    for j in range(yoko):
      Min[i][j] = round(Max[i][j] - Max[i][j] * S[i][j] / 255 ,0)
      if 0 <= H_[i][j] < 1:
        r[i][j] = Max[i][j]
        g[i][j] = round(H_[i][j] * (Max[i][j] - Min[i][j]) + Min[i][j] ,0 )
        b[i][j] = Min[i][j]
      elif 1 <= H_[i][j] < 2:
        r[i][j] = round(((120-H_add[i][j]) / 60) * (Max[i][j] - Min[i][j]) + Min[i][j] ,0)
        g[i][j] = Max[i][j]
        b[i][j] = Min[i][j]
      elif 2 <= H_[i][j] < 3:
        r[i][j] = Min[i][j]
        g[i][j] = Max[i][j]
        b[i][j] = round(((-120+H_add[i][j]) / 60) * (Max[i][j] - Min[i][j]) + Min[i][j] ,0)
      elif 3 <= H_[i][j] < 4:
        r[i][j] = Min[i][j]
        g[i][j] = round(((240-H_add[i][j]) / 60) * (Max[i][j] - Min[i][j]) + Min[i][j] ,0)
        b[i][j] = Max[i][j]
      elif 4 <= H_[i][j] < 5:
        r[i][j] = round(((-240+H_add[i][j]) / 60) * (Max[i][j] - Min[i][j]) + Min[i][j] ,0)
        g[i][j] = Min[i][j]
        b[i][j] = Max[i][j]
      elif 5 <= H_[i][j] < 6:
        r[i][j] = Max[i][j]
        g[i][j] = Min[i][j]
        b[i][j] = round(((360-H_add[i][j]) / 60) * (Max[i][j] - Min[i][j]) + Min[i][j] ,0)

  img[:, :, 2] = b
  img[:, :, 1] = g
  img[:, :, 0] = r
  img = img.astype(np.uint8) 
  return plt.imshow(img)