【问题标题】:Python Opencv drawContour errorPython Opencv drawContour 错误
【发布时间】:2017-12-17 12:19:57
【问题描述】:

它工作,但我的轮廓的颜色是黑色的。如何将其更改为红色或绿色?

    import numpy as np
    import cv2
    from matplotlib import pyplot as plt
    img = cv2.imread('1.jpg',0)
    img1 = cv2.imread('5.jpg',0)
    dest = cv2.subtract(img, img1)
    res = cv2.bitwise_not(dest)
    ret , threshold = cv2.threshold(res,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)          
    cv2.namedWindow('thresimage', cv2.WINDOW_NORMAL)
    cv2.imshow('thresimage',threshold)
    _, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    print "Number of contours detected %d -> "%len(contours)
    cv2.drawContours(threshold,contours,-1,(0,255,0),3)
    cv2.namedWindow('contour', cv2.WINDOW_NORMAL)
    cv2.imshow('contour',threshold)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

enter image description here

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    第一

    contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2:]
    

    第二

    ret , threshold = cv2.threshold(res,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) 
    # ...
    cv2.drawContours(threshold,contours,-1,(0,255,0),3)
    

    您在二进制threshed 图像上绘制颜色(0,255,0),那么它将始终是第一个元素0,即黑色。您应该先将灰色转换为 BGR,然后再绘制颜色。

    canvas = cv2.cvtColor(threshold, cv2.COLOR_GRAY2BGR)
    cv2.drawContours(canvas,contours,-1,(0,255,0),3)
    

    【讨论】:

    • 非常感谢!它可以工作,但绘制后我看不到轮廓。
    • @BùiChíThanh 发布您的结果,否则我们无法诊断。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2021-12-28
    • 2016-11-28
    • 2015-08-07
    • 2011-10-18
    • 2017-11-07
    相关资源
    最近更新 更多