【问题标题】:Masks for image with OpenCV (Python)使用 OpenCV (Python) 的图像掩码
【发布时间】:2020-10-02 21:25:19
【问题描述】:

我编写了这段代码,它创建了 2 个掩码。应用时,结果是这样的:

原图

输出

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)

我知道代码一点都不好,但可以完成工作。我该如何改进它?

【问题讨论】:

  • 您在寻找什么改进?更易读的代码?
  • 是的,可读性强,也许效率高。谢谢。

标签: python opencv mask


【解决方案1】:

以下是一些建议:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2022-06-10
    • 1970-01-01
    • 2021-08-15
    • 2014-01-10
    相关资源
    最近更新 更多