使用 Python OpenCV 追踪白色

37 投票
3 回答
96566 浏览
提问于 2025-04-17 23:30

我想用网络摄像头和Python的OpenCV库来追踪白色。其实我已经有了追踪蓝色的代码。

_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

# define range of blue color in HSV
lower_blue = np.array([110,100,100])
upper_blue = np.array([130,255,255])

#How to define this range for white color


# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(frame,frame, mask= mask)

cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)

那么,我应该给出什么样的作为追踪白色的下限和上限呢?我试着改变这些值,得到了其他颜色,但就是没法追踪到白色!!!

这些下限和上限的值是HSV值还是BGR值呢??

另外,我最后得到的结果必须是二值图像,以便进行后续处理!!

请帮帮我!!!

3 个回答

22

这是一个HSV颜色阈值脚本,可以通过滑块来确定颜色的上下限。

这里输入图片描述

结果

使用这个样本图片:

设置这些上下阈值:

lower_white = np.array([0,0,168])
upper_white = np.array([172,111,255])

我们得到了孤立的白色像素(左边)和二进制掩膜(右边)。

这是脚本,记得更改输入图片的路径。

import cv2
import sys
import numpy as np

def nothing(x):
    pass

# Load in image
image = cv2.imread('1.jpg')

# Create a window
cv2.namedWindow('image')

# create trackbars for color change
cv2.createTrackbar('HMin','image',0,179,nothing) # Hue is from 0-179 for Opencv
cv2.createTrackbar('SMin','image',0,255,nothing)
cv2.createTrackbar('VMin','image',0,255,nothing)
cv2.createTrackbar('HMax','image',0,179,nothing)
cv2.createTrackbar('SMax','image',0,255,nothing)
cv2.createTrackbar('VMax','image',0,255,nothing)

# Set default value for MAX HSV trackbars.
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)

# Initialize to check if HSV min/max value changes
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0

output = image
wait_time = 33

while(1):

    # get current positions of all trackbars
    hMin = cv2.getTrackbarPos('HMin','image')
    sMin = cv2.getTrackbarPos('SMin','image')
    vMin = cv2.getTrackbarPos('VMin','image')

    hMax = cv2.getTrackbarPos('HMax','image')
    sMax = cv2.getTrackbarPos('SMax','image')
    vMax = cv2.getTrackbarPos('VMax','image')

    # Set minimum and max HSV values to display
    lower = np.array([hMin, sMin, vMin])
    upper = np.array([hMax, sMax, vMax])

    # Create HSV Image and threshold into a range.
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower, upper)
    output = cv2.bitwise_and(image,image, mask= mask)

    # Print if there is a change in HSV value
    if( (phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
        print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
        phMin = hMin
        psMin = sMin
        pvMin = vMin
        phMax = hMax
        psMax = sMax
        pvMax = vMax

    # Display output image
    cv2.imshow('image',output)

    # Wait longer to prevent freeze for videos.
    if cv2.waitKey(wait_time) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()
61

我们来看看HSV颜色空间:

这里输入图片描述

你需要的是接近中心且比较高的白色。可以从

sensitivity = 15
lower_white = np.array([0,0,255-sensitivity])
upper_white = np.array([255,sensitivity,255])

开始,然后根据你的需求调整阈值。

你也可以考虑使用HSL颜色空间,它代表色相、饱和度和亮度。这样你只需要关注亮度来检测白色,识别其他颜色也会变得简单。HSV和HSL都会把相似的颜色放得很近。而且HSL在检测白色时可能会更准确,原因如下:

这里输入图片描述

21

我写了这个代码来追踪白色:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of white color in HSV
    # change it according to your need !
    lower_white = np.array([0,0,0], dtype=np.uint8)
    upper_white = np.array([0,0,255], dtype=np.uint8)

    # Threshold the HSV image to get only white colors
    mask = cv2.inRange(hsv, lower_white, upper_white)
    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

我尝试追踪我手机的白色屏幕,得到了这个结果:

在这里输入图片描述

你可以试着改变HSV的数值。
你也可以试试HSL颜色空间,正如Legat所说,这样会更准确。

撰写回答