OpenCV 错误: '(-215:Assertion failed) !_img.empty() in function 'imwrite'' 解决方法

这个错误通常是由于无法读取图像或图像为空导致的。可以检查图像路径是否正确或图像是否存在。如果图像存在但仍然出现错误,请检查代码中是否存在图像读取的错误或逻辑错误。以下是可能需要修改的代码示例:

  1. 检查图像路径是否正确:
import cv2

img = cv2.imread('/path/to/image.jpg')
if img is None:
    print('Error: Could not read image')
else:
    cv2.imwrite('output.jpg', img)
  1. 检查图像是否为空:
import cv2

img = cv2.imread('/path/to/image.jpg')
if img is None or img.size == 0:  # check if image is empty
    print('Error: Image is empty')
else:
    cv2.imwrite('output.jpg', img)
  1. 检查代码中是否存在图像读取的错误:
import cv2

# incorrect image path
img = cv2.imread('/incorrect/path/to/image.jpg')
if img is None:
    print('Error: Could not read image')

# incorrect file format
img = cv2.imread('/path/to/image.png')
if img is None:
    print('Error: Could not read image')

# reading image in grayscale mode
img = cv2.imread('/path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
if img is None:
    print('Error: Could not read image')
else:
    cv2.imwrite('output.jpg', img)
  1. 检查代码逻辑是否正确:
import cv2

# reading image in a loop
for i in range(10):
    img = cv2.imread('/path/to/image.jpg')
    if img is not None:
        cv2.imwrite('output_%d.jpg' % i, img)
    else:
        print('Error: Could not read image')

# writing output to a directory that does not exist
img = cv2.imread('/path/to/image.jpg')
if img is not None:
    cv2.imwrite('/path/to/output/output.jpg', img)
else:
    print('Error: Could not read image')

希望这些示例可以帮助您解决问题。

OpenCV 错误: (-215:Assertion failed) !_img.empty() in function 'imwrite' 解决方法

原文地址: https://www.cveoy.top/t/topic/oYsl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录