方法一
直接调用cv2的函数来生成,具体代码:
import cv2
img=cv2.imread("F:/Dataset/cool/1.jpg")
#change into HSV type
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)#
#change BGR to RGB
img1=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
img1=cv2.resize(img1,(600,600))
hsv=cv2.resize(hsv,(600,600))
origin=cv2.resize(img,(600,600))
cv2.imshow('BGR',origin)
cv2.imshow('hsv',hsv)
cv2.imshow('RGB',img1)
cv2.waitKey(0)
运行结果:
方法二
首先我们要先得到一张原图的BGR各自的灰度图,有两种方式得到:1.通过cv2.split分离图像的BGR分量,还有一种通过image的矩阵来得到,具体代码如下:
img='F:/Dataset/cool/1.jpg'
image=cv2.imread(img)
# 方法1
"""
B = image[:, :, 0]
G = image[:, :, 1]
R = image[:, :, 2]
"""
# 方法2
(B, G, R) = cv2.split(image) #分离图像的RBG分量
cv2.namedWindow("B",2) #创建一个窗口
cv2.imshow('B', B) #显示B分量
cv2.namedWindow("G",2) #创建一个窗口
cv2.imshow('G', G) #显示G分量
cv2.namedWindow("R",2) #创建一个窗口
cv2.imshow('R', R) #显示R分量
运行结果:
整个的转换代码如下:
import cv2
import numpy as np
def rgb2hsv(img):
h = img.shape[0]
w = img.shape[1]
H = np.zeros((h,w),np.float32)
S = np.zeros((h, w), np.float32)
V = np.zeros((h, w), np.float32)
r,g,b = cv2.split(img)
r, g, b = r/255.0, g/255.0, b/255.0
for i in range(0, h):
for j in range(0, w):
mx = max((b[i, j], g[i, j], r[i, j]))
mn = min((b[i, j], g[i, j], r[i, j]))
dt=mx-mn
if mx == mn:
H[i, j] = 0
elif mx == r[i, j]:
if g[i, j] >= b[i, j]:
H[i, j] = (60 * ((g[i, j]) - b[i, j]) / dt)
else:
H[i, j] = (60 * ((g[i, j]) - b[i, j]) / dt)+360
elif mx == g[i, j]:
H[i, j] = 60 * ((b[i, j]) - r[i, j]) / dt + 120
elif mx == b[i, j]:
H[i, j] = 60 * ((r[i, j]) - g[i, j]) / dt+ 240
H[i,j] =int( H[i,j] / 2)
#S
if mx == 0:
S[i, j] = 0
else:
S[i, j] =int( dt/mx*255)
#V
V[i, j] =int( mx*255)
return H, S, V
img=cv2.imread("F:/Dataset/cool/1.jpg")
#change into HSV type
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)#
#change BGR to RGB
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
#get h s v channels
h,s,v = rgb2hsv(img)
merged = cv2.merge([h,s,v]) #前面分离出来的三个通道
merged=np.array(merged,dtype='uint8')
merged=cv2.resize(merged,(600,600))
print(merged)
运行结果: