简体   繁体   English

OpenCV-在将图像写入文件时指定格式(cv2.imwrite)

[英]OpenCV - specify format while writing image to file (cv2.imwrite)

I want to save an image using opencv's imwrite without any extension. 我想使用没有任何扩展名的opencv的imwrite保存图像。 I know image format in cv2.imwrite is chosen based on the filename extension. 我知道cv2.imwrite图像格式是基于filename扩展filename选择的。 Is there a way to specify the compression format while calling the function, or would I have to rename the file once created? 是否可以在调用函数时指定压缩格式,还是一旦创建文件就必须重命名文件?

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_

I think it's not possible to specify the compression of an image while saving it without extension. 我认为在保存不带扩展名的图像时,不可能指定图像的压缩率。 I would recommend to save it with extension and then use os.rename() : 我建议将其保存为扩展名,然后使用os.rename()

import os
import cv2

filename = "image.jpg"
img = ...

cv2.imwrite(filename, img)
os.rename(filename, os.path.splitext(filename)[0])

Hope this helps! 希望这可以帮助!

I don't understand your motivation for doing this, but if you want to write a JPEG to disk without the .JPG extension, or a PNG file without the .PNG extension, you could simply do the encoding to a memory buffer and then write that to disk. 我不了解您这样做的动机,但是如果您想在不使用.JPG扩展名的情况下将JPEG写入磁盘,或者在不使用.PNG扩展名的情况下将PNG文件写入磁盘,则可以简单地对内存缓冲区进行编码,然后写入到磁盘上。

So, if I load an image like this: 因此,如果我加载这样的图像:

import cv2

# Load image
im = cv2.imread('image.jpg')

I should now be in the same position as you, with an image in my variable im . 我现在应该和您处于同一位置,并且在我的变量im有一个图像。

I can now encode the image to a memory buffer, and write that memory buffer to disk without extension: 我现在可以将映像编码到内存缓冲区中,然后将该内存缓冲区写入磁盘而无需扩展:

success, buffer = cv2.imencode(".jpg",im)
buffer.tofile('ExtensionlessFile') 

您可以将fileName字符串与仅在调用函数时指定扩展名的字符串连接起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM