Installation

pip install opencv-python

Reading and Saving Images

函数 cv2.imwrite()用于将图像保存到指定的文件

retval = cv2.imwrite(filename, img [, paras])

  • cv2.imwrite() 将 OpenCV 图像保存到指定的文件。
  • cv2.imwrite() 基于保存文件的扩展名选择保存图像的格式。
  • cv2.imwrite() 只能保存 BGR 3通道图像,或 8 位单通道图像、或 PNG/JPEG/TIFF 16位无符号单通道图像。

Arguments

  • filename:要保存的文件的路径和名称,包括文件扩展名
  • img:要保存的 OpenCV 图像,nparray 多维数组
  • paras:不同编码格式的参数,可选项
    • cv2.CV_IMWRITE_JPEG_QUALITY:设置 .jpeg/.jpg 格式的图片质量,取值为 0-100(默认值 95),数值越大则图片质量越高;
    • cv2.CV_IMWRITE_WEBP_QUALITY:设置 .webp 格式的图片质量,取值为 0-100;
    • cv2.CV_IMWRITE_PNG_COMPRESSION:设置 .png 格式图片的压缩比,取值为 0-9(默认值 3),数值越大则压缩比越大。
  • retval:返回值,保存成功返回 True,否则返回 False。

Notice

  • cv2.imwrite() 保存的是 OpenCV 图像(多维数组),不是 cv2.imread() 读取的图像文件,所保存的文件格式是由 filename 的扩展名决定的,与读取的图像文件的格式无关。
  • 对 4 通道 BGRA 图像,可以使用 Alpha 通道保存为 PNG 图像。
  • cv2.imwrite() 指定图片的存储路径和文件名,在 python3 中不支持中文和空格(但并不会报错)。必须使用中文时,可以使用 cv2.imencode() 处理,参见扩展例程。

Examples

# 1.4 图像的保存
imgFile = "../images/logoCV.png"  # 读取文件的路径
img3 = cv2.imread(imgFile, flags=1)  # flags=1 读取彩色图像(BGR)

saveFile = "../images/imgSave.png"  # 保存文件的路径
# cv2.imwrite(saveFile, img3, [int(cv2.IMWRITE_PNG_COMPRESSION), 8])  # 保存图像文件, 设置压缩比为 8
cv2.imwrite(saveFile, img3)  # 保存图像文件
# 1.5 保存中文路径的图像
imgFile = "../images/logoCV.png"  # 读取文件的路径
img3 = cv2.imread(imgFile, flags=1)  # flags=1 读取彩色图像(BGR)

saveFile = "../images/测试图02.jpg"  # 带有中文的保存文件路径
# cv2.imwrite(saveFile, img3)  # imwrite 不支持中文路径和文件名,读取失败,但不会报错!
img_write = cv2.imencode(".jpg", img3)[1].tofile(saveFile)

Debug

OpenCv error: (-2) could not find a writer for the specified extension in function cv::imwrite_

Didn’t specify the extension name for the image to be saved so that OpenCv cannot tell which encoder to use.