Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用opencv(python3中的cv2)检测对象是否具有3种颜色中的特定颜色_Python 3.x_Opencv_Cv2_Color Detection - Fatal编程技术网

Python 3.x 使用opencv(python3中的cv2)检测对象是否具有3种颜色中的特定颜色

Python 3.x 使用opencv(python3中的cv2)检测对象是否具有3种颜色中的特定颜色,python-3.x,opencv,cv2,color-detection,Python 3.x,Opencv,Cv2,Color Detection,我目前正在开发一个程序,可以检测我房间里是否有红色物体,或者是否有蓝色物体。我周围的其他部分不是白色就是黑色。我尽量减少房间里光线的变化 我已经成功地在给定一定色调范围的对象周围创建了一个遮罩。我想让我的程序为我打印: 1) “红色”-如果有红色对象 2) “蓝色”-如果有蓝色对象 我不知道如何继续。下面是我的程序,它在蓝色的物体周围涂上遮罩。我也给出了一些其他颜色的色调范围。这样你就可以试试了 该方案: import cv2 import numpy as np cam = cv2.Vide

我目前正在开发一个程序,可以检测我房间里是否有红色物体,或者是否有蓝色物体。我周围的其他部分不是白色就是黑色。我尽量减少房间里光线的变化

我已经成功地在给定一定色调范围的对象周围创建了一个遮罩。我想让我的程序为我打印:

1) “红色”-如果有红色对象

2) “蓝色”-如果有蓝色对象

我不知道如何继续。下面是我的程序,它在蓝色的物体周围涂上遮罩。我也给出了一些其他颜色的色调范围。这样你就可以试试了

该方案:

import cv2
import numpy as np

cam = cv2.VideoCapture(1)

while True:
    _, frame = cam.read()

    denoised = cv2.GaussianBlur(frame, (31, 31), 35)
    hsv = cv2.cvtColor(denoised, cv2.COLOR_BGR2HSV)


    lower_blue = np.array([110, 50, 50])
    upper_blue = np.array([160, 255, 255])

    mask = cv2.inRange(hsv, lower_red, upper_red)
    res = cv2.bitwise_and(frame, frame, mask=mask)

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

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cam.release()
cv2.destroyAllWindows()
不同颜色的色调(我不确定红色的色调,因为它不适用于某些颜色-我尝试了Stackoverflow的几种解决方案):

以下是一些您可以尝试的示例图像:


你的方法在某种程度上是正确的。但要确定图像特定区域的颜色,需要计算已知颜色数据集与区域的L*a*b平均值之间的欧氏距离

  • 检测需要颜色的特定感兴趣区域
  • 参考以下代码确定感兴趣区域内的颜色

    class ColorLabeler:
        def __init__(self):
            # initialize the colors dictionary, containing the color
            # name as the key and the RGB tuple as the value
            colors = OrderedDict({
                "red": (255, 0, 0),
                "green": (0, 255, 0),
                "blue": (0, 0, 255)})
    
            # allocate memory for the L*a*b* image, then initialize
            # the color names list
            self.lab = np.zeros((len(colors), 1, 3), dtype="uint8")
            self.colorNames = []
    
            # loop over the colors dictionary
            for (i, (name, rgb)) in enumerate(colors.items()):
                # update the L*a*b* array and the color names list
                self.lab[i] = rgb
                self.colorNames.append(name)
    
            # convert the L*a*b* array from the RGB color space
            # to L*a*b*
            self.lab = cv2.cvtColor(self.lab, cv2.COLOR_RGB2LAB)
    
    def label(self, image, c):
        # construct a mask for the contour, then compute the
        # average L*a*b* value for the masked region
        mask = np.zeros(image.shape[:2], dtype="uint8")
        cv2.drawContours(mask, [c], -1, 255, -1)
        mask = cv2.erode(mask, None, iterations=2)
        mean = cv2.mean(image, mask=mask)[:3]
    
        # initialize the minimum distance found thus far
        minDist = (np.inf, None)
    
        # loop over the known L*a*b* color values
        for (i, row) in enumerate(self.lab):
            # compute the distance between the current L*a*b*
            # color value and the mean of the image
            d = dist.euclidean(row[0], mean)
    
            # if the distance is smaller than the current distance,
            # then update the bookkeeping variable
            if d < minDist[0]:
                minDist = (d, i)
    
        # return the name of the color with the smallest distance
        return self.colorNames[minDist[1]]
    
    类彩色标签机:
    定义初始化(自):
    #初始化包含颜色的颜色字典
    #name作为键,RGB元组作为值
    颜色=有序的颜色({
    “红色”:(255,0,0),
    “绿色”:(0,255,0),
    “蓝色”:(0,0255)})
    #为L*a*b*映像分配内存,然后初始化
    #颜色名称列表
    self.lab=np.zero((len(颜色),1,3),dtype=“uint8”)
    self.colorNames=[]
    #在颜色字典上循环
    对于枚举(colors.items())中的(i,(名称,rgb)):
    #更新L*a*b*数组和颜色名称列表
    self.lab[i]=rgb
    self.colorNames.append(名称)
    #从RGB颜色空间转换L*a*b*阵列
    #到L*a*b*
    self.lab=cv2.cvt颜色(self.lab,cv2.COLOR\u RGB2LAB)
    def标签(自身、图像、c):
    #为轮廓构造一个遮罩,然后计算
    #遮罩区域的平均L*a*b*值
    掩码=np.0(image.shape[:2],dtype=“uint8”)
    cv2.绘制轮廓(掩模,[c],-1255,-1)
    掩模=cv2。腐蚀(掩模,无,迭代次数=2)
    平均值=cv2。平均值(图像,遮罩=遮罩)[:3]
    #初始化迄今为止找到的最小距离
    minDist=(np.inf,无)
    #循环已知的L*a*b*颜色值
    对于枚举(self.lab)中的(i,行):
    #计算当前L*a*b之间的距离*
    #颜色值和图像的平均值
    d=距离欧几里德(行[0],平均值)
    #如果距离小于当前距离,
    #然后更新簿记变量
    如果d
    • 上面的代码是从PyImageSearch中借来的,您可以在这里找到完整的博文以供参考:()
  • class ColorLabeler:
        def __init__(self):
            # initialize the colors dictionary, containing the color
            # name as the key and the RGB tuple as the value
            colors = OrderedDict({
                "red": (255, 0, 0),
                "green": (0, 255, 0),
                "blue": (0, 0, 255)})
    
            # allocate memory for the L*a*b* image, then initialize
            # the color names list
            self.lab = np.zeros((len(colors), 1, 3), dtype="uint8")
            self.colorNames = []
    
            # loop over the colors dictionary
            for (i, (name, rgb)) in enumerate(colors.items()):
                # update the L*a*b* array and the color names list
                self.lab[i] = rgb
                self.colorNames.append(name)
    
            # convert the L*a*b* array from the RGB color space
            # to L*a*b*
            self.lab = cv2.cvtColor(self.lab, cv2.COLOR_RGB2LAB)
    
    def label(self, image, c):
        # construct a mask for the contour, then compute the
        # average L*a*b* value for the masked region
        mask = np.zeros(image.shape[:2], dtype="uint8")
        cv2.drawContours(mask, [c], -1, 255, -1)
        mask = cv2.erode(mask, None, iterations=2)
        mean = cv2.mean(image, mask=mask)[:3]
    
        # initialize the minimum distance found thus far
        minDist = (np.inf, None)
    
        # loop over the known L*a*b* color values
        for (i, row) in enumerate(self.lab):
            # compute the distance between the current L*a*b*
            # color value and the mean of the image
            d = dist.euclidean(row[0], mean)
    
            # if the distance is smaller than the current distance,
            # then update the bookkeeping variable
            if d < minDist[0]:
                minDist = (d, i)
    
        # return the name of the color with the smallest distance
        return self.colorNames[minDist[1]]