OpenCV findContours仅间歇性地工作

时间:2019-03-11 23:48:43

标签: python opencv opencv-python

我目前正在运行一个使用drawContours()概述轮廓的非常基本的脚本。不幸的是,它只能正确运行约1/5次,每次都必须手动关闭并重新加载脚本,以等待findContours正常工作。

这是脚本和我在做什么的图片(当drawContours脚本工作时)

import cv2
import os

cap = cv2.VideoCapture(0)
cv2.namedWindow("val", cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty("val",cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)

while True:
    ret, val = cap.read()
    image = cv2.cvtColor(val, cv2.COLOR_BGR2GRAY)
    cnts,__ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for i in cnts:
        area = cv2.contourArea(i)
        print("Area: {}".format(area))
        if area > 100:
            cv2.drawContours(val,i,-1, (0,0,255),1)
    cv2.imshow('val', val)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

Me with contours outlined

2 个答案:

答案 0 :(得分:2)

查找轮廓最适合边缘/二进制图像,例如cv2.threshold或cv2.adaptiveThreshold

请参见contour tutorial

答案 1 :(得分:0)

尝试对图像进行阈值处理

ret, thresh = cv2.threshold(image, 127, 255, 0)

,然后尝试找到国家/地区:

cnts,__ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
相关问题