python - 我正在尝试检测图像中红色对象的轮廓,但在使用 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 图像
解决方案
再见,
我认为这个片段可以解决您的问题。由于您对轮廓感兴趣,我会在扩张之前应用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()
祝你有美好的一天,
安东尼诺
推荐阅读
- android - OneSignal.init 尚未被调用。将订阅操作移动到等待任务队列
- reactjs - 在 Nginx Docker 容器中运行 React 应用程序的问题
- python - 如何再次将其转换为元组键值列表?
- ios - iOS 操作扩展未打开我的主应用程序
- angular - 如何使用 Ionic 4 项目将 Angular 版本更新为 8
- javascript - 将 ul(无序列表)保持在固定位置
- r - 在新表中合并 2 列并删除重复项
- android - MDC Button MaterialShapeDrawable 奇怪的阴影并且没有波纹
- javascript - 比较 JSON 数组和 JSON 对象并找出差异
- javascript - Ramda:折叠一个对象