furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

OpenCV: error: (-215:Assertion failed) !_img.empty() in function 'imwrite' [GB]

Error

cv2.error: OpenCV(4.1.2) /io/opencv/modules/imgcodecs/src/loadsave.cpp:715: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'

means you try to write empty array (empty image).

You can get the same error using empty array.

import cv2
import numpy as np

cv2.imwrite('img.png', np.array([]))

But if you add at least one element then it works without error.

import cv2
import numpy as np

cv2.imwrite('img.png', np.array([0]))

Directly before imwrite you can check shape or size of array to confirm it.

import cv2
import numpy as np

arr = np.array([])

print('shape:', arr.shape)
print('size:', arr.size)
print('--- arr ---\n', arr, '\n--- end ---')

cv2.imwrite('img.png', arr)

This code will works without error because array is not empty.

import cv2
import numpy as np

arr = np.array([
    [  0,   0,   0],
    [  0, 255,   0],
    [  0,   0,   0],
], dtype='uint8')

print('shape:', arr.shape)
print('size:', arr.size)
print('--- arr ---\n', arr, '\n--- end ---')

cv2.imwrite('img.png', arr)

cv2.imshow('image', arr)
cv2.waitKey(0)
cv2.destroyWindow()
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury