圖片顏色空間檢測(cè)代碼
原文
rub01.jpg
rub00.jpg
import cv2,time,argparse,glob
import numpy as np
# 鼠標(biāo)回調(diào)函數(shù)
def showPixelValue(event,x,y,flags,param):
global img, combinedResult, placeholder
if event == cv2.EVENT_MOUSEMOVE:
# 從鼠標(biāo)所在位置獲取像素值 (x,y)
bgr = img[y,x]
# 將BGR像素轉(zhuǎn)換為其他顏色格式
ycb = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2YCrCb)[0][0]
lab = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2Lab)[0][0]
hsv = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2HSV)[0][0]
# 創(chuàng)建一個(gè)空的占位符以顯示值
placeholder = np.zeros((img.shape[0],400,3),dtype=np.uint8)
# 用顏色空間的值填充占位符
cv2.putText(placeholder, "BGR {}".format(bgr), (20, 70), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)
cv2.putText(placeholder, "HSV {}".format(hsv), (20, 140), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)
cv2.putText(placeholder, "YCrCb {}".format(ycb), (20, 210), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)
cv2.putText(placeholder, "LAB {}".format(lab), (20, 280), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)
# 合并兩個(gè)結(jié)果以在單個(gè)圖像中并排顯示
combinedResult = np.hstack([img,placeholder])
cv2.imshow('P< N>',combinedResult)
鍵盤P上一張圖 鍵盤N下一張圖
# 加載圖像并設(shè)置鼠標(biāo)回調(diào)函數(shù)
global img
files = glob.glob('images/rub*.jpg')
files.sort()
img = cv2.imread(files[0])
img = cv2.resize(img,(400,400))
cv2.imshow('P< N>',img)
# 創(chuàng)建一個(gè)空窗口
cv2.namedWindow('P< N>')
# 為鼠標(biāo)上的任何事件創(chuàng)建一個(gè)回調(diào)函數(shù)
cv2.setMouseCallback('P< N>',showPixelValue)
i = 0
while(1):
k = cv2.waitKey(1) & 0xFF
# 檢查文件夾中的下一張圖像
if k == ord('n'):
i += 1
img = cv2.imread(files[i%len(files)])
img = cv2.resize(img,(400,400))
cv2.imshow('P< N>',img)
# 檢查文件夾中的上一張圖像
elif k == ord('p'):
i -= 1
img = cv2.imread(files[i%len(files)])
img = cv2.resize(img,(400,400))
cv2.imshow('P< N>',img)
elif k == 27:
cv2.destroyAllWindows()
break