Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect / Avoid "Premature end of JPEG" in cv2 - python

Tags:

python

opencv

I have a stream of images saved to a file (like every 2 seconds) from outside program (can't control it). When I try to read that image, sometimes, it is read while it is being written, so I get the message from OpenCV about the end of the JPEG. Is there a way to test if the file is bad, and if so to wait a while and then try to re-read it?

Thanks...

like image 749
Omer Avatar asked Dec 02 '22 13:12

Omer


1 Answers

I researched a little about this "error", and it appears to be a warning in C which python cannot detect properly. It's a very tough issue, and happens because the image is not complete. Detecting if the image ends properly (with b'\xff\xd9' characters) seems to work:

with open(os.path.join(path, file), 'rb') as f:
    check_chars = f.read()[-2:]
if check_chars != b'\xff\xd9':
    print('Not complete image')
else:
    imrgb = cv2.imread(os.path.join(path, file), 1)
like image 182
Alberto Jaenal Avatar answered Dec 06 '22 11:12

Alberto Jaenal