Python:检测黑色方块 [英] Python: detect black squares

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

问题描述

我正在尝试检测黑色正方形.

I'm trying to detect the black square.

这是我的代码使用者...

Here is my code sofar...

    frame=cv2.imread('squares.jpg')
    img=cv2.GaussianBlur(frame, (5,5), 0)

    img=cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    lower=np.array([0, 0, 0],np.uint8)
    upper=np.array([10, 50, 50],np.uint8)
    separated=cv2.inRange(img,lower,upper)


    #this bit draws a red rectangle around the detected region
    contours,hierarchy=cv2.findContours(separated,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
    max_area = 0
    largest_contour = None
    for idx, contour in enumerate(contours):
        area = cv2.contourArea(contour)
        if area > max_area:
            max_area = area
            largest_contour=contour
            if not largest_contour==None:
                moment = cv2.moments(largest_contour)
                if moment["m00"] > 1000:
                    rect = cv2.minAreaRect(largest_contour)
                    rect = ((rect[0][0], rect[0][1]), (rect[1][0], rect[1][1]), rect[2])
                    (width,height)=(rect[1][0],rect[1][1])
                    print str(width)+" "+str(height)
                    box = cv2.cv.BoxPoints(rect)
                    box = np.int0(box)
                    if(height>0.9*width and height<1.1*width):
                            cv2.drawContours(frame,[box], 0, (0, 0, 255), 2)

    cv2.imshow('img',frame)

然后我尝试在检测到的黑色区域周围绘制一个红色正方形.

I'm then trying to draw a red square around the detected black region.

该代码适用于具有以下参数的黄色,橙色,红色和绿色:

The code works for yellow, orange, red and green with the following parameters:

colours=['yellow','orange','red','green','black','white']
uppers=[[20,100,100],[5,100,100],[0,100,100],[???,???,???],[???,???,???]]
lowers=[[30,255,255],[15,255,255],[6,255,255],[???,???,???],[???,???,???]]

我就是黑白色都无法工作...

I just can't get black or white to work...

有什么想法吗?

推荐答案

此处的主要直觉是,黑色位于

The key intuition here is that black is located at all hue and saturation values in the HSV cylinder, but only at low value values. I found that a lower bound [0, 0, 0] and an upper bound [180, 255, 50] will locate the black square, like so:

我还应该提到,由于以下几个原因,您的方法无法找到白色方块:

I should also mention that your method will not work for finding the white squares, for several reasons:

  • 存在多个白色方块.您的方法仅选择最大的轮廓,这意味着每种颜色只能检测到一个正方形.
  • 很难将白色方块"与打印在其上的纸张颜色区分开.您可能会得到一个单一的轮廓,将正方形和两侧的纸条连接起来.

这篇关于Python:检测黑色方块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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