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
相依套件:
- pip install opencv-python
- pip install py-linq # https://viralogic.github.io/py-enumerable/
程式:
- from py_linq import Enumerable
- import cv2
- import numpy as np
- def get_hue(img):
- ''' 圖片色相 '''
- img = cv2.resize(img, (32, 32), interpolation = cv2.INTER_LINEAR)
- img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
- pixel_hsv = np.reshape(img_hsv,(-1,3))
- result = Enumerable(pixel_hsv)\
- .order_by_descending(lambda p: p[2])\
- .then_by_descending(lambda p: p[1])\
- .first()
- print(f'[result]: {result}')
- return result[0]
- def get_gray_rate(hue):
- ''' 根據色相計算灰階比例 '''
- hue_full = np.uint8([[[hue,255,255]]])
- hue_bgr = cv2.cvtColor(hue_full, cv2.COLOR_HSV2BGR)
- (hue_b, hue_g, hue_r) = hue_bgr[0,0]
- hue_total = 0.0 + hue_b + hue_g + hue_r
- return [
- hue_b / hue_total,
- hue_g / hue_total,
- hue_r / hue_total,
- ]
- img = cv2.imread('01.jpg')
- hue = get_hue(img)
- gray_rate = get_gray_rate(hue) # 灰階比例
- print(f'hue:{hue}, gray_rate: {gray_rate}')
- # 灰階轉換
- img_gray = cv2.transform(img, np.array([gray_rate]))
- cv2.imshow("img", img)
- cv2.imshow("img_gray", img_gray)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
0 回應:
張貼留言