用于识别对象之间关系的OpenCv技术

时间:2016-07-02 05:52:20

标签: python opencv

我是OpenCV的新手,但试图解决以下问题:

目标图像中的每个“精灵”看起来都一样,但它们的排列方式会有所不同:

Problem

目前我正在尝试保持简单和高对比度。

我的问题与技术有关:

1)我是否应该使用模板匹配并尝试在提取对象后提取对象的关系? 2)我应该使用下面的模式构建我自己的Haar级联吗?

精灵之间的距离会在我的样本图像中发生变化,但精灵每次都会相同。

感谢您的帮助;

安迪

2 个答案:

答案 0 :(得分:1)

有两个简单的步骤可以解决这个问题而不使用haar级联。

  1. 对图像进行二值化并在图像上应用findContours函数,通过该函数可以从中唯一地识别每个精灵,您可能会找到精灵的颜色。

  2. 现在在轮廓上应用boundingRect函数,然后找到每个精灵的中心点。检查每个精灵的x坐标是否相等然后它们在同一条线上。如果y轴相等则它们是堆叠的。如果两者不相等则为角度精灵

答案 1 :(得分:1)

抱歉花了这么长时间。

正如我前面提到的,我没有使用boundingRect函数。相反,我使用另一种方法来查找精灵的边界。我将解释下面的代码

最初我将图像裁剪为

1sprite.png 2linesprite.png 3linesprite.png 2stacksprite.png 3stacksprite.png anglesprite

步骤1:读取输入图像。

第2步:将源图像转换为灰度图像

步骤3:通过阈值处理将灰度图像转换为二值图像。

步骤4:将findContour函数应用于二进制图像。

步骤5:如果没有轮廓,退出。如果它只有一个轮廓,则打印1个方形精灵并退出。如果有多个精灵寻找中心等等。

步骤6:使用瞬间找到轮廓的中心并绘制 轮廓为蓝色。

步骤7:在精灵上绘制中心点并找到x和y坐标所在的位置。

步骤8:最后打印精灵模板。

import cv2
import os
import sys
import numpy as np

### inintialization #######

centre =[]
moments=[]
initX=0
initY=0
flagLine=0
flagStack=0

######### Reading input image#########

source = cv2.imread("C:/Prabhakar/Data/anglesprite.png")
cv2.imshow("SourceDisplay", source)
#### Creating Empty matrix ####
binaryImage = np.zeros(source.shape, np.uint8)
#### GrayScale Conversion ####
gray = cv2.cvtColor(source,cv2.COLOR_BGR2GRAY)
#### Binarization ###
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)

cv2.imshow("Binary Image", thresh)
##### Finding Contour #####
im2, contours, hierarchy =cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

#print "No.of Contours:",len(contours)

###### Finding Center of the contour also drawing it ######

if(len(contours)==0):
    print "No Square found!!"
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    sys.exit(0)
elif(len(contours)==1):
    print "It is a Square!!"
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    sys.exit(0)
else:    
    for cnts in contours:
    moments = cv2.moments(cnts)
    centre.append((int(moments['m10']/moments['m00']), int(moments['m01']/moments['m00'])))
    cv2.drawContours(binaryImage, contours, -1, (255,0,0), -1)

    #print centre
    ##### Findind Sprite Template #####
    for i in range(len(centre)):

        initX=centre[0][0]
        initY=centre[0][1]
        cv2.circle(binaryImage, centre[i], 1, (0, 0, 255), -1)
        if(centre[i][0]>=initX-2 and centre[i][0]<=initX+2):
            flagStack = flagStack+1
        if(centre[i][1]>=initY-2 and centre[i][1]<=initY+2):
            flagLine = flagLine+1


    if(flagLine == len(contours)):
         print "It is a ",len(contours),"Square Line"

    elif(flagStack == len(contours)):
        print "It is a ",len(contours),"Square Stack"

    else:
        print "It is a ",len(contours),"Square Angle"

    cv2.imshow("Contour Image", binaryImage)
cv2.waitKey(0)
cv2.destroyAllWindows()

如果您有任何疑问,请将其留在评论中。

相关问题