gpt4 book ai didi

python - 检测图像中白色背景的有效方法

转载 作者:行者123 更新时间:2023-12-04 03:52:04 79 4
gpt4 key购买 nike

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

这个过程需要时间,如果我有很多图像,这个过程会特别长。在 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

最佳答案

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

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

关于python - 检测图像中白色背景的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64304446/

79 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com