【发布时间】: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