python - OpenCV 中的方向检测出现问题

标签 python opencv orientation object-detection canny-operator

我正在尝试制作一个计算机视觉脚本来检测物体的方向。它在大多数情况下都有效,但似乎对于某些图像无法取得同样的成功。

该脚本依靠模糊和 Canny 边缘检测来查找轮廓。

工作示例:

enter image description here

失败的部分: enter image description here

enter image description here

对于失败的部分,它是相同形状之一的两条线,并且完全忽略其他形状之一。

主要代码:

import cv2
from imgops import imutils
import CVAlgo

z = 'am'

path = 'images/pca.jpg'
#path = 'images/pca2.jpg'

img = cv2.imread(path)
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

img = imutils.resize(img, height = 600)
imgray = imutils.resize(img, height = 600)

final = img.copy()

thresh, imgray = CVAlgo.filtering(img, imgray, z)


__ , contours, hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# Iterate through all contours
test = CVAlgo.cnt_gui(final, contours)

#cv2.imwrite('1.jpg', final)

cv2.imshow('thresh', thresh)
cv2.imshow('contours', final)
cv2.waitKey(0)

CVAlgo.py

import cv2
from numpy import *
from pylab import *
from imgops import imutils
import math

def invert_img(img):
    img = (255-img)
    return img


def canny(imgray):
    imgray = cv2.GaussianBlur(imgray, (11,11), 200)
    canny_low = 0
    canny_high = 100

    thresh = cv2.Canny(imgray,canny_low,canny_high)
    return thresh

def cnt_gui(img, contours):
    cnts = sorted(contours, key = cv2.contourArea, reverse = True)

    for i in range(0,len(cnts)):
        sel_cnts = sorted(contours, key = cv2.contourArea, reverse = True)[i]

        area = cv2.contourArea(sel_cnts)

        if area < 1000:
            continue

        # get orientation angle and center coord
        center, axis,angle = cv2.fitEllipse(sel_cnts)

        hyp = 100  # length of the orientation line

        # Find out coordinates of 2nd point if given length of line and center coord 
        linex = int(center[0]) + int(math.sin(math.radians(angle))*hyp)
        liney = int(center[1]) - int(math.cos(math.radians(angle))*hyp)

        # Draw orienation
        cv2.line(img, (int(center[0]),int(center[1])), (linex, liney), (0,0,255),5)             
        cv2.circle(img, (int(center[0]), int(center[1])), 10, (255,0,0), -1)

    return img

def filtering(img, imgray, mode):
    imgray = cv2.medianBlur(imgray, 11)
    thresh = cv2.Canny(imgray,75,200)

    return thresh, imgray

有谁知道问题出在哪里吗?有人知道我该如何改进这个脚本吗?

最佳答案

未检测到的形状太接近黑色背景,因此其轮廓已与白色对象区域的轮廓合并。您在其中一个对象中找到的第二个方向实际上是外部轮廓的方向。为了避免其中的一些问题,您可以在阈值化后使用 cv2.dilate 函数来扩大或关闭二值图像:cv2.dilate .

关于python - OpenCV 中的方向检测出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34471863/

相关文章:

python - 从 csv 文件中加载 url 列表,并针对相同的数据对它们进行逐一解析

python - 从 PyQt GUI 类外部访问 GUI 元素 text( )

c - 如何旋转和缩放单应性

ios - 如何以编程方式设置设备(UI)方向?

iOS 8 在应用程序启动时检测设备方向

php - 是否有与 TCPDF 的 'annotate' 函数等效的 python ReportLab?

python - 是否可以在R中的 “autodetec”函数之后为每个对话确定说话者

c++ - 经纱透视

python - OpenCV使用单色相机将帧扔到输出时得到3张图片而不是1张

java - Android getOrientation 问题 - 沿轴镜像值