使用opencv检测具有特定颜色的圆圈 [英] Detect circles with specific colors using opencv

查看:166
本文介绍了使用opencv检测具有特定颜色的圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用OpenCV和python检测图像中的黄色圆圈,如第一幅图像所示:

I have to detect yellow circles in an image using OpenCV and python, as shown in the first image:

一旦检测到黄色圆圈,就必须突出显示它,就像这样:

Once I detect the yellow circle, I have to highlight it, like so:

我是OpenCV的新手,所以我正在寻找指导或帮助.感谢所有帮助

I am new to OpenCV, so I was looking for some guidance or help. All help is appreciated

推荐答案

这是一种可能的方法:

  • 将图像转换为HSV
  • 找到上下颜色边界并创建遮罩
  • 查找轮廓并使用顶点数进行过滤

我们将图像转换为HSV,然后使用cv2.inRange()确定上下边界以创建蒙版.此步骤将黄色物体隔离出来

We convert image to HSV and then determine lower and upper boundaries to create a mask using cv2.inRange(). This step isolates the yellow objects

image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([0, 208, 94], dtype="uint8")
upper = np.array([179, 255, 232], dtype="uint8")
mask = cv2.inRange(image, lower, upper)

接下来要确定形状,我们找到轮廓并使用顶点数进行过滤.我们使用cv2.arcLength()cv2.approxPolyDP()获得顶点和近似轮廓的列表.我们可以检查此列表中的条目数,以确定对象的形状.例如,如果轮廓具有三个顶点,则它必须是三角形.同样,如果它有四个顶点,则它必须是一个正方形.因此,对于此图像,我们可以假设形状具有大于一定数量的顶点的形状为圆形.这是结果

Next to determine the shape, we find contours and filter using the number of vertices. We use cv2.arcLength() and cv2.approxPolyDP() to obtain a list of vertices and approximate contours. We can check the number of entries in this list to determine the shape of an object. For instance, if the contour has three vertices, it must be a triangle. Similarly, if it has four vertices, it must be a square. So for this image, we can make the assumption the shape is a circle if it has greater than a certain number of vertices. Here's the result

import numpy as np
import cv2

image = cv2.imread('1.png')
original = image.copy()
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([0, 208, 94], dtype="uint8")
upper = np.array([179, 255, 232], dtype="uint8")
mask = cv2.inRange(image, lower, upper)

# Find contours
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Extract contours depending on OpenCV version
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

# Iterate through contours and filter by the number of vertices 
for c in cnts:
    perimeter = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * perimeter, True)
    if len(approx) > 5:
        cv2.drawContours(original, [c], -1, (36, 255, 12), -1)

cv2.imshow('mask', mask)
cv2.imshow('original', original)
cv2.imwrite('mask.png', mask)
cv2.imwrite('original.png', original)
cv2.waitKey()

这篇关于使用opencv检测具有特定颜色的圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆