简体   繁体   中英

How to convert a single BGR array to HSV array in Python with OpenCV?

I am writing a Python program for image tracking in which I receive input BGR values for min and max values and then filter a live video feed to only show values between those min and max values. While the input is in BGR, I need to filter the video using HSV. However, I am having trouble figuring out how to convert my single BGR input arrays into HSV arrays in numpy without having to use the cvtColor function on the entire image.

From my understanding, it seems like the cv2.cvtColor() function will only work on the entire image but I need to be able to convert just these select min and max BGR arrays to HSV before I do the color tracking.

Whenever I run this code I get the following error from the OpenCV code from the cvtColor function call.

OpenCV Error: Assertion failed (depth == CV_8U || depth == CV_16U || depth == CV_32F) in cv::cvtColor, file D:\\Build\\OpenCV\\opencv-3.2.0\\modules\\imgproc\\src\\color.cpp, line 9710

I have tried using the BGR arrays, which works but I specifically need to use HSV here.

What is the cleanest way to solve this problem? Please let me know if I can provide more information, thanks. I'm still pretty new to Python.

minBGR = np.array([minB, minG, minR])
maxBGR = np.array([maxB, maxG, maxR])

minHSV = cv2.cvtColor(minBGR, cv2.COLOR_BGR2HSV)
maxHSV = cv2.cvtColor(maxBGR, cv2.COLOR_BGR2HSV)

mask = cv2.inRange(hsvFrame, minHSV, maxHSV)

By default, numpy creates arrays with the minimum type necessary to hold them.

Om my 64-bit system, creating arrays from values in the range 0 to 255 creates int64 arrays.

In [1]: import numpy as np

In [2]: np.array([0,0,0])
Out[2]: array([0, 0, 0])

In [3]: a = np.array([0,0,0])

In [4]: a.dtype
Out[4]: dtype('int64')

In [5]: a = np.array([255,255,255])

In [6]: a.dtype
Out[6]: dtype('int64')

This is an 8-byte integer:

In [20]: dt = np.dtype('>i8')

In [21]: dt.itemsize
Out[21]: 8

In [22]: dt.name
Out[22]: 'int64'

You probably want to create uint8 or uint16 arrays.

In [7]: a = np.array([0,0,0], dtype=np.uint8)

In [8]: b = np.array([255,255,255], dtype=np.uint8)

In [9]: a.dtype, b.dtype
Out[9]: (dtype('uint8'), dtype('uint8'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM