首页 > 解决方案 > 我正在尝试检测图像中红色对象的轮廓,但在使用 openCv cv.findContour 函数时不断出现错误

问题描述

我正在尝试获取图像一部分的轮廓,但是当我调用 cv.findContour 图像时,我不断收到错误消息。为了在图像中找到对象,我首先尝试提取对象的颜色,即红色,然后尝试在检测到的对象上找到轮廓。

import cv2 as cv
import numpy as np


def main():

    image_find_goal = "image.jpg"
    kernel = np.ones((5,5),np.uint8)
    #findGoal(image_find_goal)
    img1 = cv.imread(image_find_goal)
    img = cv.resize(img1,(700,700))
    hsv = cv.cvtColor(img,cv.COLOR_BGR2HSV)

    #range for red color
    lower_r = np.array([160,100,100])
    upper_r = np.array([179,255,255])
    mask = cv.inRange(hsv,lower_r,upper_r)
    res = cv.bitwise_and(img,img,mask=mask)
    _,thresh = cv.threshold(res,125,255,cv.THRESH_BINARY)
    dilate =  cv.dilate(thresh,None,iterations=1)

    contours, hierarchy = cv.findContours(dilate,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
    for cnt in contours:
        epsilon = 0.1*cv.arcLength(cnt,True)
        approx = cv.approxPolyDP(cnt,epsilon,True)
        if len(approx) == 4:
            cv.drawContours(img,cnt,-1,(60,255,255),4)

    cv.imshow('OBSTACLES',img)
    cv.waitKey(0)
    cv.destroyWindow(img)

我得到的错误是:

轮廓,层次结构 = cv.findContours(dilate,cv.RETR_TREE,cv.CHAIN_APPROX_NONE) cv2.error: OpenCV(4.4.0) /tmp/pip-req-build-sw_3pm_8/opencv/modules/imgproc/src/contours.cpp :195:错误:(-210:不支持的格式或格式组合)[开始]FindContours 仅在模式时支持 CV_8UC1 图像!= CV_RETR_FLOODFILL 否则仅在函数 'cvStartFindContours_Impl' 中支持 CV_32SC1 图像

标签: pythonopencvobject-detection

解决方案


再见,

我认为这个片段可以解决您的问题。由于您对轮廓感兴趣,我会在扩张之前应用Canny 边缘检测。此举还将修复您遇到的 CV 类型错误

import cv2 as cv
import numpy as np

image_find_goal = "image.jpg"
#findGoal(image_find_goal)
img1 = cv.imread(image_find_goal)
img = cv.resize(img1,(700,700))
hsv = cv.cvtColor(img,cv.COLOR_BGR2HSV)

#range for red color
lower_r = np.array([160,100,100])
upper_r = np.array([179,255,255])
mask = cv.inRange(hsv,lower_r,upper_r)
res = cv.bitwise_and(img,img,mask=mask)
_,thresh = cv.threshold(res,125,255,cv.THRESH_BINARY)

# check which are the best canny threshold values for your image
imgCanny = cv.Canny(thresh, 180, 180)
dilate = cv.dilate(imgCanny, None, iterations = 1)
# cv.imshow("dilate", dilate)
# cv.waitKey()

contours, hierarchy = cv.findContours(dilate,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
for cnt in contours:
    epsilon = 0.1*cv.arcLength(cnt,True)
    approx = cv.approxPolyDP(cnt,epsilon,True)
    if len(approx) == 4:
        cv.drawContours(img,cnt,-1,(60,255,255),4)

cv.imshow('OBSTACLES',img)
cv.waitKey(0)
cv.destroyAllWindows()

祝你有美好的一天,
安东尼诺


推荐阅读