【问题标题】:Fill the outside of contours OpenCV填充轮廓OpenCV的外部
【发布时间】:2016-10-21 03:25:41
【问题描述】:

我正在尝试使用 openCV 和 python 语言将轮廓的外部区域涂成黑色。 这是我的代码:

contours, hierarchy = cv2.findContours(copy.deepcopy(img_copy),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]
# how to fill of black the outside of the contours cnt please? `

【问题讨论】:

    标签: python image python-2.7 opencv opencv-contour


    【解决方案1】:

    以下是在一组轮廓之外用黑色填充图像的方法:

    import cv2
    import numpy
    img = cv2.imread("zebra.jpg")
    stencil = numpy.zeros(img.shape).astype(img.dtype)
    contours = [numpy.array([[100, 180], [200, 280], [200, 180]]), numpy.array([[280, 70], [12, 20], [80, 150]])]
    color = [255, 255, 255]
    cv2.fillPoly(stencil, contours, color)
    result = cv2.bitwise_and(img, stencil)
    cv2.imwrite("result.jpg", result)
    

    UPD.:上面的代码利用了 bitwise_and 与 0-s 产生 0-s 的事实,并且不适用于黑色以外的填充颜色。填充任意颜色:

    import cv2
    import numpy
    
    img = cv2.imread("zebra.jpg")
    
    fill_color = [127, 256, 32] # any BGR color value to fill with
    mask_value = 255            # 1 channel white (can be any non-zero uint8 value)
    
    # contours to fill outside of
    contours = [ numpy.array([ [100, 180], [200, 280], [200, 180] ]), 
                 numpy.array([ [280, 70], [12, 20], [80, 150]])
               ]
    
    # our stencil - some `mask_value` contours on black (zeros) background, 
    # the image has same height and width as `img`, but only 1 color channel
    stencil  = numpy.zeros(img.shape[:-1]).astype(numpy.uint8)
    cv2.fillPoly(stencil, contours, mask_value)
    
    sel      = stencil != mask_value # select everything that is not mask_value
    img[sel] = fill_color            # and fill it with fill_color
    
    cv2.imwrite("result.jpg", img)
    

    也可以用另一个图像填充,例如,使用img[sel] = ~img[sel] 代替img[sel] = fill_color 会用轮廓外的相同倒置图像填充它:

    【讨论】:

    • 谢谢兄弟',我很感激。无论什么时候,你在丹佛,找我,我会帮你一个忙
    • @Bill 如果这回答了您的问题,请接受/投票。不需要人情;D
    • @Miki,放弃我的青睐,当你得到它们时拒绝你的! :)
    • @Headcrab 真的很抱歉...无论何时您在米兰,请联系我...我会帮您一个忙 ;D
    • @Mvk1312 这取决于图像类型。为什么,你要填充白色而不是黑色?
    猜你喜欢
    • 2013-10-13
    • 2014-11-26
    • 1970-01-01
    • 2014-04-05
    • 2020-06-14
    • 2019-06-28
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多