首頁 > 後端開發 > Python教學 > 如何使用OpenCV Python找到一種顏色的HSV值?

如何使用OpenCV Python找到一種顏色的HSV值?

王林
發布: 2023-08-19 14:25:14
轉載
936 人瀏覽過

如何使用OpenCV Python找到一种颜色的HSV值?

要找到一個顏色的HSV值,我們可以使用從BGRHSV的色彩空間轉換。首先,我們將顏色值以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.

import cv2
import numpy as np
登入後複製

為顏色定義一個numpy.ndarraydtype=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.

Example 1

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)
登入後複製

Example 2

的中文翻譯為:

範例 2

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中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板