代码之家  ›  专栏  ›  技术社区  ›  lucians

带opencv(python)的图像掩码

  •  0
  • lucians  · 技术社区  · 8 年前

    我编写了这个代码,它创建了2个遮罩。应用后,结果如下:

    原始图像 original

    产量 output

    import cv2
    import numpy as np
    
    frame = cv2.imread('image.jpg')
    
    h, w = frame.shape[:2]
    
    upper_value = int(h / 10) * 5
    lower_value = -(int(h / 10) * 3)
    
    upper_mask = cv2.rectangle(frame, (0, 0), (w, upper_value), (0, 50, 255), -1)
    lower_mask = cv2.rectangle(frame, (0, upper_value + int(h / 10) * 5), (w, upper_value + int(h / 10) * 2), (0, 50, 255), -1)
    

    我知道代码,它一点都不好,但做它是工作。我该如何改进?

    谢谢

    1 回复  |  直到 8 年前
        1
  •  3
  •   Jundiaius    8 年前

    以下是一些建议:

    import cv2
    import numpy as np
    
    frame = cv2.imread('image.jpg')
    
    h, w = frame.shape[:2]
    mask_color = (0, 50, 255) # isolate a repeating constant
    
    # avoid setting a variable that is used only once, only if you REALLY need it to improve readability
    # that's why `upper_value` and `lower_value` were removed. 
    # BTW, `lower_value` was unused in your code.
    
    upper_mask = cv2.rectangle(frame, (0, 0), (w, int(0.5 * h)), mask_color, -1)
    lower_mask = cv2.rectangle(frame, (0, h), (w, int(0.7 * h)), mask_color, -1)