我也一直在努力寻找解决方案。看了几十篇文章,大部分只是说openCV不抛出错误,只在stderr上输出错误。
有些人建议使用 PIL,但这并不能检测到大多数图像损坏。通常只是提前结束文件。
然而,OpenCV 警告的相同错误可以通过 imagemagick 检测到。
- 安装 imagemagick (https://imagemagick.org/)
- 确保在路径中有它。
- 将以下子代码放入您的代码并调用它以从您需要的任何地方验证文件。它还会向 stderr 输出错误,但会引发错误(感谢“-regard-warnings”)
import subprocess
def checkFile(imageFile):
try:
subprocess.run(["identify", "-regard-warnings", imageFile]).check_returncode()
return true
except (subprocess.CalledProcessError) as e:
return false
如果您不希望检查向您的输出发送垃圾邮件,请将 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL 参数添加到 run 函数调用。
如果您尚未安装旧版命令,则在 windows 上使用新语法:
subprocess.run(["magick", "identify", "-regard-warnings", imageFile]).check_returncode()