Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to save an image using opencv's imwrite without any extension. I know image format in cv2.imwrite is chosen based on the filename extension. 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_
like image 273
kampta Avatar asked May 03 '16 17:05

kampta


People also ask

What is Imwrite in cv2?

cv2. imwrite() method is used to save an image to any storage device. This will save the image according to the specified format in current working directory. Syntax: cv2.imwrite(filename, image)

Does cv2 Imwrite compress?

Save Image to File in JPEG Format This is because cv2. imwrite() has the ability to compress the image while writing it into the file.

Does cv2 Imwrite overwrite Python?

imwrite will overwrite existing files without outputting an error or asking for confirmation. Image of any format can be saved using this method.

What format is the image read in using OpenCV?

OpenCV offers support for the image formats Windows bitmap (bmp), portable image formats (pbm, pgm, ppm) and Sun raster (sr, ras).


1 Answers

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.

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.

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') 
like image 132
Mark Setchell Avatar answered Sep 22 '22 08:09

Mark Setchell