gpt4 book ai didi

python - 我正在尝试检测图像中红色物体上的轮廓,但是在使用openCv cv.findContour函数时始终出现错误

转载 作者:行者123 更新时间:2023-12-02 17:58:14 33 4
gpt4 key购买 nike

我正在尝试获取图像一部分的轮廓,但是在调用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)
我得到的错误是:

contours, hierarchy =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:error: (-210:Unsupported format or combination of formats)[Start]FindContours supports only CV_8UC1 images when mode !=CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function'cvStartFindContours_Impl'

最佳答案

再见,
我认为这段代码可以解决您的问题。由于您对Contours感兴趣,因此我会在扩展前应用Canny Edge Detection。此举还将解决您遇到的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()
祝你有美好的一天,
安东诺

关于python - 我正在尝试检测图像中红色物体上的轮廓,但是在使用openCv cv.findContour函数时始终出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64200224/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com