如何解决我正在尝试检测图像中红色物体上的轮廓,但是在使用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,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),4)
cv.imshow('OBSTACLES',img)
cv.waitKey(0)
cv.destroyWindow(img)
我得到的错误是:
轮廓,层次结构= cv.findContours(膨胀,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)cv2。错误: 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否则仅在函数中支持CV_32SC1图像 'cvStartFindContours_Impl'
解决方法
Ciao
我认为此片段解决了您的问题。由于您对轮廓有兴趣,因此在进行扩张之前,请先应用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,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),4)
cv.imshow('OBSTACLES',img)
cv.waitKey(0)
cv.destroyAllWindows()
祝你有美好的一天,
安东尼诺
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。