2023-03-14 13:56

[OpenCV] 以最亮顏色的色相來進行灰階處理

OpenCV-Python 教學 https://docs.opencv.org/3.4.16/d6/d00/tutorial_py_root.html

原始圖片

原圖因為燈光散射的關係,整個圖片都出現發紅的現象


預設灰階 cv2.imread('01.jpg', cv2.IMREAD_GRAYSCALE)

有部分的色差變得不明顯,之後要進行辨識變得很困難


色相比例的灰階

透過色相的方式就好很多


HSV 的數值定義

  • H: 色相 0~360度
  • S: 飽和度 0~1
  • V: 明度 (黑)0~1(白)

OpenCV HSV 的數值定義

  • H: 0 ~ 180 => H / 2
  • S: 0 ~ 255 => S * 255
  • V: 0 ~ 255 => V * 255

相依套件:

  1. pip install opencv-python 
  2. pip install py-linq     # https://viralogic.github.io/py-enumerable/ 

程式:

  1. from py_linq import Enumerable 
  2. import cv2 
  3. import numpy as np 
  4.  
  5.  
  6. def get_hue(img): 
  7.    ''' 圖片色相 ''' 
  8.  
  9.    img = cv2.resize(img, (32, 32), interpolation = cv2.INTER_LINEAR) 
  10.    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 
  11.    pixel_hsv = np.reshape(img_hsv,(-1,3)) 
  12.  
  13.    result = Enumerable(pixel_hsv)\ 
  14.        .order_by_descending(lambda p: p[2])\ 
  15.        .then_by_descending(lambda p: p[1])\ 
  16.        .first() 
  17.  
  18.    print(f'[result]: {result}') 
  19.    return result[0] 
  20.  
  21.  
  22.  
  23. def get_gray_rate(hue): 
  24.    ''' 根據色相計算灰階比例 ''' 
  25.  
  26.    hue_full = np.uint8([[[hue,255,255]]]) 
  27.    hue_bgr = cv2.cvtColor(hue_full, cv2.COLOR_HSV2BGR) 
  28.    (hue_b, hue_g, hue_r) = hue_bgr[0,0] 
  29.  
  30.    hue_total =  0.0 + hue_b + hue_g + hue_r 
  31.  
  32.    return [ 
  33.        hue_b / hue_total, 
  34.        hue_g / hue_total, 
  35.        hue_r / hue_total, 
  36.    ] 
  37.  
  38.  
  39.  
  40. img = cv2.imread('01.jpg') 
  41.  
  42. hue = get_hue(img) 
  43. gray_rate = get_gray_rate(hue) # 灰階比例 
  44.  
  45. print(f'hue:{hue}, gray_rate: {gray_rate}') 
  46.  
  47. # 灰階轉換 
  48. img_gray = cv2.transform(img, np.array([gray_rate])) 
  49.  
  50. cv2.imshow("img", img) 
  51. cv2.imshow("img_gray", img_gray) 
  52. cv2.waitKey(0) 
  53. cv2.destroyAllWindows() 

0 回應: