Opencv - 如何找到轮廓(箭头)方向

时间:2016-11-27 15:51:03

标签: python image opencv

我有这样的图像 sample

带有一堆箭头的

我想知道图像上大多数箭头的方向是什么。

我做了一些关于opencv的阅读,并提出了以下代码

import numpy as np
import cv2
import math

img = cv2.imread('sample7.png')
height, width, channels = img.shape 
img = cv2.resize(img, (width*8, height*8))                    
img = cv2.medianBlur(img,5)
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)


ret,th1 = cv2.threshold(imgray,100,255,cv2.THRESH_BINARY)
edged=cv2.Canny(th1,127,200)


im2,contours,h = cv2.findContours(edged.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
(img2,cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
screenCnt=None
flag_t=False
flag_s=False

kot=[]

for c in cnts:
    approx = cv2.approxPolyDP( c, 0.01*cv2.arcLength(c,True), True )

    area = cv2.contourArea(c)
    #print area
    if int(len(approx)) > 8 and area > 600 and area < 1100: 
        anglelist=[]
        cv2.drawContours(img, [approx], -1, (0, 255, 255), 1)
        (x,y),(MA,ma),angle = cv2.fitEllipse(c)
        print round(angle,-1)
        kot.append(round(angle,-1))


d = {}
for elm in kot:
    d[elm] = d.get(elm, 0) + 1
counts = [(j,i) for i,j in d.items()]
count, max_elm = max(counts)


print 'most common:'
print max_elm
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

通过我的脚本,我可以获得一些准确的结果。问题是如果箭头朝上或朝下,向左或向右,我会得到相同的结果。如何知道箭头是指向左还是右?在下面的图片的两种情况下,我在90度左右得到相同的结果。 enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

如果不了解某些计算机视觉基础知识,这将是一项艰巨的任务。我的方法是用opencv读取图像,这会留下一个numpy数组。将其加载为灰度图像,并使用像sobel滤镜一样的掩模来检测边缘。更好的是,精明的操作员。最好先看看这些以及它们是如何工作的。通过这些,您可以检测图像中的边缘及其方向。你可以使用它。另一个更高级(可能更好)的选项是使用霍夫变换,它能够检测图像中的线条(或任何其他几何对象)。这些都包含在opencv中,但您可能需要了解它们的工作原理。希望这会有所帮助。