OpenCV - 在将图像写入文件时指定格式 (cv2.imwrite)
OpenCV - specify format while writing image to file (cv2.imwrite)
我想使用 opencv 的 imwrite
保存图像,不带任何扩展名。我知道 cv2.imwrite
中的图像格式是根据 filename
扩展名选择的。有没有办法在调用函数时指定压缩格式,或者我是否必须在创建后重命名文件?
cv2.imwrite(filename, img)
[Out]: /home/travis/miniconda/conda-bld/work/opencv-3.1.0/modules/imgcodecs/src/loadsave.cpp:459: error: (-2) could not find a writer for the specified extension in function imwrite_
您可以在调用函数时将 fileName 字符串与仅指定扩展名的字符串连接起来。
我认为在不扩展的情况下保存图像时无法指定图像的压缩率。我建议用扩展名保存它,然后使用 os.rename()
:
import os
import cv2
filename = "image.jpg"
img = ...
cv2.imwrite(filename, img)
os.rename(filename, os.path.splitext(filename)[0])
希望对您有所帮助!
我不明白你这样做的动机,但如果你想将不带 .JPG
扩展名的 JPEG 文件或不带 .PNG
扩展名的 PNG 文件写入磁盘,你可以只需对内存缓冲区进行编码,然后将其写入磁盘。
所以,如果我像这样加载图像:
import cv2
# Load image
im = cv2.imread('image.jpg')
我现在应该和你处于同样的位置,在我的变量中有一个图像im
。
我现在可以将图像编码到内存缓冲区,并将该内存缓冲区不带扩展名写入磁盘:
success, buffer = cv2.imencode(".jpg",im)
buffer.tofile('ExtensionlessFile')
我想使用 opencv 的 imwrite
保存图像,不带任何扩展名。我知道 cv2.imwrite
中的图像格式是根据 filename
扩展名选择的。有没有办法在调用函数时指定压缩格式,或者我是否必须在创建后重命名文件?
cv2.imwrite(filename, img)
[Out]: /home/travis/miniconda/conda-bld/work/opencv-3.1.0/modules/imgcodecs/src/loadsave.cpp:459: error: (-2) could not find a writer for the specified extension in function imwrite_
您可以在调用函数时将 fileName 字符串与仅指定扩展名的字符串连接起来。
我认为在不扩展的情况下保存图像时无法指定图像的压缩率。我建议用扩展名保存它,然后使用 os.rename()
:
import os
import cv2
filename = "image.jpg"
img = ...
cv2.imwrite(filename, img)
os.rename(filename, os.path.splitext(filename)[0])
希望对您有所帮助!
我不明白你这样做的动机,但如果你想将不带 .JPG
扩展名的 JPEG 文件或不带 .PNG
扩展名的 PNG 文件写入磁盘,你可以只需对内存缓冲区进行编码,然后将其写入磁盘。
所以,如果我像这样加载图像:
import cv2
# Load image
im = cv2.imread('image.jpg')
我现在应该和你处于同样的位置,在我的变量中有一个图像im
。
我现在可以将图像编码到内存缓冲区,并将该内存缓冲区不带扩展名写入磁盘:
success, buffer = cv2.imencode(".jpg",im)
buffer.tofile('ExtensionlessFile')