【问题标题】:Detecting Red and Blue Squares (beanbags) using Python and CV2使用 Python 和 CV2 检测红色和蓝色方块(豆袋)
【发布时间】:2017-05-19 14:53:17
【问题描述】:

我是 CV2 的新手,我正在寻找有关应用程序的一些高级指导。我正在开发一个程序,可以检测相机框架中的红色和蓝色豆袋。我使用了 openCV 提供的示例代码来检测蓝色并稍微修改它以检测红色。

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

cap = cv2.VideoCapture(0)

while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])
    lower_red = np.array([-20, 100, 100])
    upper_red = np.array([13, 255, 255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_red, upper_red)

    # 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()

这是(稍作修改)从 OpenCV 站点复制和粘贴的代码。我正在寻找正确的方法来分析维度<460, 640, 3>res numpy 数组,以便检测到

  1. 我的屏幕上有红色/蓝色对象
  2. 使用此信息执行某些操作,例如 print(1 red and 2 blue squares detected)

图片链接: Input, res and mask image of blue beanbag

【问题讨论】:

  • 请更新您的帖子,使用示例图片和您目前的结果。
  • 我刚刚这样做了,如果有帮助请告诉我。
  • 你能把输入的图片也贴出来吗?
  • 完成(屏幕空间不足哈哈)。

标签: python opencv image-processing colors detection


【解决方案1】:

您将需要获得两个面具,一个用于红色,另一个用于蓝色:

mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)

现在让我们定义一个函数,它检测掩码中的给定区域是否高于阈值以决定是否存在豆袋,为此我们将使用cv2.findContours

def is_object_present(mask, threshold):
    im, contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    # Find the largest contour
    largest_contour = max(contours, key=lambda x:cv2.contourArea(x))
    if cv2.contourArea(largest_contour) > threshold:
        return True
    return False

现在您在两个掩码上调用此方法,如果存在红豆袋或蓝豆袋,则获取单独的值:

# Adjust this manually as per your needs
bean_bag_area_threshold = 5000
is_red_bean_bag_present = is_object_present(mask_red, bean_bag_area_threshold)
is_blue_bean_bag_present = is_object_present(mask_blue, bean_bag_area_threshold)

if is_red_bean_bag_present and is_blue_bean_bag_present:
    print "Both bean bags are present." 

【讨论】:

  • 谢谢,很好的回应。您能否对以下行的操作添加评论:1.im, contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  • 哦,我的错,我附上了documentation的链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
  • 2014-08-26
  • 2012-08-03
相关资源
最近更新 更多