
要找到一个颜色的HSV值,我们可以使用从BGR到HSV的颜色空间转换。首先,我们将颜色值以BGR格式定义为numpy.ndarray,然后将其转换为HSV空间。
We can also find the lower and upper limits of HSV value as [H-10, 100, 100] and [H+10, 255, 255] respectively. These lower and upper limits can be used to track an object of particular color.
要找到一个颜色的HSV值,请按照以下步骤进行:
Import the required libraries. In all the following Python examples, the required Python libraries are OpenCV and NumPy. Make sure you have already installed them.
立即学习“Python免费学习笔记(深入)”;
import cv2 import numpy as np
为颜色定义一个numpy.ndarray,dtype=np.uint8。
green = np.uint8([[[0, 255, 0]]])
Convert the above defined color to HSV.
hsvGreen = cv2.cvtColor(green, cv2.COLOR_BGR2HSV)
Print the color values.
print("HSV of Green:", hsvGreen)
Let's look at some program examples to understand it clearly.
In this example, we find the HSV value for green color. The BGR value of green is [0,255,0].
# import required libraries
import numpy as np
import cv2
# define a numpy.ndarray for the color
# here insert the bgr values which you want to convert to hsv
green = np.uint8([[[0, 255, 0]]])
# convert the color to HSV
hsvGreen = cv2.cvtColor(green, cv2.COLOR_BGR2HSV)
# display the color values
print("BGR of Green:", green)
print("HSV of Green:", hsvGreen)
# Compute the lower and upper limits
lowerLimit = hsvGreen[0][0][0] - 10, 100, 100
upperLimit = hsvGreen[0][0][0] + 10, 255, 255
# display the lower and upper limits
print("Lower Limit:",lowerLimit)
print("Upper Limit", upperLimit)
When you run the above Python program, it will produce the following output −
BGR of Green: [[[ 0 255 0]]] HSV of Green: [[[ 60 255 255]]] Lower Limit: (50, 100, 100) Upper Limit (70, 255, 255)
In this example, we find the HSV value for a color whose BGR value is [106,76,89].
# import required libraries
import numpy as np
import cv2
green = np.uint8([[[0, 255, 0]]])
# convert the color to HSV
hsvGreen = cv2.cvtColor(green, cv2.COLOR_BGR2HSV)
# here insert the bgr values which you want to convert to hsv
bgr = np.uint8([[[106,76,89]]])
hsv = cv2.cvtColor(green, cv2.COLOR_BGR2HSV)
print("BGR Value:", bgr)
print("HSV Value:", hsv)
# compute the lower and upper limits
lowerLimit = hsvGreen[0][0][0] - 10, 100, 100
upperLimit = hsvGreen[0][0][0] + 10, 255, 255
# display the lower and upper limits
print("Lower Limit:",lowerLimit)
print("Upper Limit", upperLimit)
When you run the above python program, it will produce the following output −
BGR Value: [[[76 76 89]]] HSV Value: [[[ 60 255 255]]] Lower Limit: (50, 100, 100) Upper Limit (70, 255, 255)
以上就是如何使用OpenCV Python找到一种颜色的HSV值?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号