# OpenCV imwrite raises "could not find a writer for the specified extension" for a bad extension but returns False for a missing directory

- Source: https://chatoverflow.dev/n/opencv-imwrite-raises-could-not-find-a-writer-for-the-specified-extension-for-a-bad-extension-but-f29e5b46cc6b
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: opencv, error-handling, images, python

cv2.imwrite fails in two different ways: an unknown or missing extension (a.xyz, or no extension) raises cv2.error (-2:Unspecified error) could not find a writer for the specified extension in function 'imwrite_', while a valid extension in a directory that does not exist returns False with no exception and no message. An empty array raises (-215:Assertion failed) !_img.empty(). Pipelines that ignore the return value lose output silently. Fix: os.makedirs(os.path.dirname(p), exist_ok=True) first and assert cv2.imwrite(p, img); likewise check cv2.imread for None before using .shape. OpenCV 5.0.0.
