方法1:使用自带函数实现
from tkinter.tix import IMAGE
import cv2
import mpmath
import numpy as np
from numba import uint8
from streamlit.error_util import handle_uncaught_app_exception
image=cv2.imread("image\\p2.jpg")
cv2.imshow("p1",image)
cv2.waitKey(0)
cv2.destroyAllWindows()
image1=cv2.resize(image,(500,500))
cv2.imshow("p1",image1)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Convert the BGR image to HSV Image
hsv_img = cv2.cvtColor(image1, cv2.COLOR_BGR2HSV)
cv2.imwrite('hsv_image.jpg', hsv_img)
h,s,v = cv2.split(hsv_img)
# Display the HSV image
cv2.imshow('HSV (cvtColor)', hsv_img)
cv2.waitKey(0)
#cv2.destroyAllWindows()
方法2:自己编写算法
//函数实现
def rgb_to_hsv(r, g, b):
# 将RGB值转换为0-1范围内的百分比
r = r / 255.0
g = g / 255.0
b = b / 255.0
# 计算最大值和最小值
max_value = max(r, g, b)
min_value = min(r, g, b)
# 计算色相(Hue)
hue=0
if max_value == min_value:
hue = 0
elif max_value == r:
if g>b:
hue = 60*((g - b) / (max_value - min_value))
elif g<b:
hue = 60*((g - b) / (max_value - min_value))+360
elif max_value == g:
hue = 60*((b - r) / (max_value - min_value)) + 120
elif max_value == b:
hue = 60*((r - g) / (max_value - min_value)) + 240
#print(hue)
hue =int(hue/2)
# 计算饱和度(Saturation)
if max_value == 0:
saturation = 0
else:
saturation = 1 - (min_value / max_value)
saturation=int(saturation*255)
# 计算明度(Value)
value = max_value
value=int(value*255)
return hue,saturation, value
# 示例:将RGB颜色(128, 64, 192)转换为HSV颜色
B, G, R = cv2.split(image1)
#声明hsv三个通道
h_mask=np.zeros([500,500],dtype="uint8")
s_mask=np.zeros([500,500],dtype="uint8")
v_mask=np.zeros([500,500],dtype="uint8")
#整个图片遍历
for j in range(499,-1,-1):
for i in range(499, -1, -1):
print(j,i)
hsv = rgb_to_hsv(R[j, i], G[j, i], B[j, i])
h_mask[j, i] = hsv[0]
s_mask[j, i] = hsv[1]
v_mask[j, i] = hsv[2]
print(hsv)
image3=cv2.merge((h_mask,s_mask,v_mask))
cv2.imshow("my_rgb_to_hsv",image3)
cv2.waitKey(0)
cv2.destroyAllWindows()