如何使用OpenCV过滤颜色?代码示例

2021年4月2日09:36:45 发表评论 1,525 次浏览

颜色分割或颜色过滤在OpenCV中广泛用于识别具有特定颜色的特定对象/区域。使用最广泛的色彩空间是RGB色彩空间, 它称为加性色彩空间

三种颜色的总和就可以赋予图像颜色。要确定特定颜色的区域, 请设置阈值并创建一个遮罩以分离不同的颜色。 HSV颜色空间为此目的更为有用, 因为HSV空间中的颜色更加局限, 因此可以轻松分离。彩色滤镜具有许多应用和用例, 例如在密码学, 红外分析, 易腐食品的食品保存等方面。在这种情况下, 图像处理的概念可用于发现或提取出特定颜色的区域。

对于颜色分割, 我们所需要的只是阈值或一种颜色空间中颜色的上下限范围的知识。它在"色相饱和度值"色彩空间中效果最佳。

在指定要分割的颜色范围之后, 需要相应地创建一个遮罩, 并通过使用它可以分离出特定的关注区域。

下面是代码:

import cv2
import numpy as np
  
cap = cv2.VideoCapture( 0 )
  
while ( 1 ):
     _, frame = cap.read()
     # It converts the BGR color space of image to HSV color space
     hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
      
     # Threshold of blue in HSV space
     lower_blue = np.array([ 35 , 140 , 60 ])
     upper_blue = np.array([ 255 , 255 , 180 ])
  
     # preparing the mask to overlay
     mask = cv2.inRange(hsv, lower_blue, upper_blue)
      
     # The black region in the mask has the value of 0, # so when multiplied with original image removes all non-blue regions
     result = cv2.bitwise_and(frame, frame, mask = mask)
  
     cv2.imshow( 'frame' , frame)
     cv2.imshow( 'mask' , mask)
     cv2.imshow( 'result' , result)
      
     cv2.waitKey( 0 )
  
cv2.destroyAllWindows()
cap.release()

原始图片-

使用OpenCV过滤颜色1

遮罩图像

使用OpenCV过滤颜色2

蓝色分段区域-

使用OpenCV过滤颜色3

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: