使用OpenCV确定图像中物体的颜色

您所在的位置:网站首页 怎样识别颜色区分图片和名称 使用OpenCV确定图像中物体的颜色

使用OpenCV确定图像中物体的颜色

2024-07-11 13:49| 来源: 网络整理| 查看: 265

1 前言

在这里插入图片描述

这是我们关于形状检测和分析的三部分系列的最后一篇文章。

以前,我们学习了如何:

计算轮廓的中心执行形状检测和识别

今天,我们将对图像中的对象执行形状检测和颜色标记。

在这一点上,我们理解图像的区域可以通过颜色直方图和基本颜色通道统计信息(例如均值和标准差)来表征。

但是,尽管我们可以计算这些统计数据,但它们无法为我们提供实际的标签,例如将区域标记为包含特定颜色的“红色”,“绿色”,“蓝色”或“黑色”。

在此博客文章中,我将详细介绍如何利用L*a*b*颜色空间以及欧几里德距离来使用Python和OpenCV标记,标注和确定图像中对象的颜色。

2 使用OpenCV确定对象颜色

在深入研究任何代码之前,让我们简要回顾一下我们的项目结构:

|--- pyimagesearch | |--- __init__.py | |--- colorlabeler.py | |--- shapedetector.py |--- detect_color.py |--- example_shapes.png

注意我们如何重用我们先前博客文章中的shapedetector.py和ShapeDetector类。我们还将创建一个新文件colorlabeler.py,该文件将使用颜色的文本标签标记图像区域。

最后,将使用detect_color.py驱动程序脚本将所有片段粘合在一起。

在继续阅读本文之前,请确保已在系统上安装了imutils Python软件包:

$ pip install imutils

在本课程的其余部分中,我们将在该库中使用各种功能。

2.1 标记图像中的颜色

该项目的第一步是创建一个Python类,该类可用于用其关联的颜色标记图像中的形状。

为此,我们在colorlabeler.py文件中定义一个名为ColorLabeler的类:

# import the necessary packages from scipy.spatial import distance as dist from collections import OrderedDict import numpy as np import cv2 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)

第2-5行导入我们所需的Python程序包,而第7行定义ColorLabeler类。

然后我们进入第8行的构造函数。首先,我们需要初始化一个colors字典(第11-14行),该字典指定颜色名称(字典的键)到RGB元组(字典的值)。

从那里,我们为NumPy数组分配内存以存储这些颜色,然后初始化颜色名称列表(第18和19行)。

下一步是遍历colors字典,然后分别更新NumPy数组和colorNames列表(第22-25行)。

最后,我们将NumPy“图像”从RGB颜色空间转换为L*a*b*颜色空间。

那么为什么我们使用L*a*b*颜色空间而不是RGB或HSV?

好吧,为了实际地标记和标记图像的区域包含某种颜色,我们将计算已知colors的数据集(即lab数组)与特定图像区域的平均值之间的欧几里得距离。

使欧几里德距离最小的已知颜色将被选作颜色标识。

而且与HSV和RGB颜色空间不同,L*a*b*颜色之间的欧几里得距离具有实际的感知意义,因此在本文的其余部分中将使用它。

下一步是定义label方法:

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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3