【问题标题】:Efficient way to detect white background in image检测图像中白色背景的有效方法
【发布时间】:2021-01-25 23:24:42
【问题描述】:

我编写了一个脚本来检测图像是否具有白色背景,方法是汇总所有白色像素以及它是否超过总像素的阈值百分比。

如果我有很多图像,这个过程需要时间,尤其是长时间。在 numpy 或 opencv 中是否有更有效的方法可以做到这一点,而不仅仅是使用并行处理?

def find_white_background(imgpath, threshold="0.3"):
    """remove images with transparent or white background"""
    imgArr = cv2.imread(imgpath)
    w, h, alpha = imgArr.shape

    total = w * h
    background = np.array([255, 255, 255])

    cnt = 0
    for row in imgArr:
        for pixel in row:
            if np.array_equal(pixel, background):
                cnt += 1

    percent = cnt / total
    if percent >= threshold:
        return True
    else:
        return False

【问题讨论】:

  • 这并不能区分“正确的”背景和混入大量白色的前景。举个极端的例子:黑白棋盘是一个带有黑色方块的白色背景,还是带有白色方块的黑色背景?
  • 我认为这很好,因为用例是在网络中为特定对象抓取图像,并且我不希望该对象位于白色背景中,此逻辑可以轻松识别

标签: python python-3.x algorithm image optimization


【解决方案1】:

这应该通过一次将整个数组与背景颜色数组进行比较而不是循环来提​​供更高的效率。

def find_white_background(imgpath, threshold=0.3):
    """remove images with transparent or white background"""
    imgArr = cv2.imread(imgpath)
    background = np.array([255, 255, 255])
    percent = (imgArr == background).sum() / imgArr.size
    if percent >= threshold:
        print(percent)
        return True
    else:
        return False

【讨论】:

    猜你喜欢
    • 2015-08-16
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多