python - 如何处理CV2(Cv2.imwrite)中的错误?

标签 python python-3.x opencv error-handling opencv-python

我正在尝试解决cv2.imwrite不断抛出的错误,它不断到达文件夹中的相同图像,然后在cv2.imwrite行说“-215:断言失败”,而我写的运气并不好失败的保险柜为该类型的错误,它正在正确读取,所以我不知道为什么它不会写。
我尝试了以下两种方法:

        writeStatus = cv2.imwrite('output/'+ i, cropped)
        if writeStatus is True:
            print('Image Written')
        else:
            print('Error saving photo')
            cv2.imwrite('rejected/'+ i, image)
        if cv2.imwrite('output/'+ i, cropped) == True:
            print('Image write succeeded')
        else:
            if cv2.imwrite('rejected/'+ i, image)== True:
                print ('Cropped image could not be written, sent to rejects')
            else:
                print('writing error, script stopped')
                break
我不知道为什么它不保存图像,到目前为止,它似乎只讨厌这个特定的图像,即使图像仅在文件夹中也不会写,我也不会在乎,只要我能输出这样的图像即可。拒绝文件夹,而不是杀死整个脚本。
编辑尝试使用的
        writeStatus = cv2.imwrite('output/'+ i, cropped)
        if writeStatus is True:
            print('Image Written')
        else:
            print('Error saving photo')
            continue
并且错误仍然停止了脚本

最佳答案

建议#1

如果我们看一下语句:

writeStatus = cv2.imwrite('output/'+ i, cropped)
'output/' + i应该是图像名称,裁剪后应该是图像。
据我了解,您想保存i th值,但是正确的方法是:
from os.path import join

filename = join('output', str(i) + '.png') # you can use other extensions like .jpg
cv2.imwrite(filename, cropped)
但是,如果cropped变量是图像,则为true。
建议2

如果单个图像引起问题并且您不在乎,则可以使用try-except块和continue关键字
try:
    writeStatus = cv2.imwrite(...)
    .
    .
except:
    continue

关于python - 如何处理CV2(Cv2.imwrite)中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63564966/

相关文章:

python-3.x - Python3 SMTP 'Connection unexpectedly closed'

python - QSqlQuery中isValid()的解释

opencv - 从特征关键点在 OpenCV 中手动进行成对匹配

python - NN VBD IN DT NNS RB 在 NLTK 中是什么意思?

Python - 带有字母数字的人类数字,但在 pyQt 和 __lt__ 运算符中

python-3.x - Gekko优化问题中IMODE的选择

python - Numpy 创建一个空的 alpha 图像

python - 无法在 macOS 上的 Anaconda3 python3.6 上安装 OpenCV3

Python datetime.strptime().timetuple() - 'str' 对象不可调用

python - Python 新手 : Interactive Broker API function