Search code examples
pythonimageopencvface-recognition

how to fix this"OSError: cannot identify image file " Opencv imwrite doesn't actually save image


I'm learning Opencv right now from this git

https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam_faster.py

and add some code tocapture image, it does capture and save image to my specified path but it doesn't show image it saved (sorry,i'm not sure what to call it) it say doesn't support this format file

![1]: https://ibb.co/zXp7PmY

i tried change format file to jpg,bmp,png moved these code in/out of for loop add

top = 200
right = 200
bottom = 200
left = 200

if not in imshow for loop

poor_match_index = np.argmax(face_distances)            
           if matches[poor_match_index]:
               cv2.imwrite("tanapat/unknown_" + str(count) + ".jpg", frame[right:left,top:bottom]) 
               unknown = face_recognition.load_image_file("tanapat/unknown_"+ str(count) +".jpg")
               unknown_encoding = face_recognition.face_encodings(unknown )[0]
               known_face_encodings.append(unknown_encoding)
               known_face_names.append("unknown_"+str(count))
               name = known_face_names[poor_match_index]
               count +=1
               break

i tried to make it repeat to capture new face and recognize it(try to not make it continue to capture the same person too many frame)

but got error on line

unknown = face_recognition.load_image_file("tanapat/unknown_"+ str(count) +".jpg")

OSError: cannot identify image file 'tanapat/unknown_0.jpg'


Solution

  • If you use

    top = 200
    right = 200
    bottom = 200
    left = 200
    

    then frame[200:200,200:200] creates empty array.

     width = right - left = 200 - 200 = 0
     height = bottom - top = 200 - 200 = 0
    

    When you save empty array then you get empty file - my Linux shows size 0 for this .jpg - and you can't open empty file.

    You need at least

    top = 200
    bottom = top + 1  # 201
    
    left = 200
    right = left + 1  # 201
    

    to create file with one pixel - frame[200:201,200:201].


    If you use print() to display result from imwrite()

    print(cv2.imwrite(...))
    

    then you get False if it had problem to save file.