12

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_
kampta
  • 4,748
  • 5
  • 31
  • 51

3 Answers3

4

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():

import os
import cv2

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

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

Hope this helps!

linusg
  • 6,289
  • 4
  • 28
  • 78
  • 1
    The motivation is we can *successfully* read an image file without extension but we would *fail* in saving it using the same name. Reading an image, processing it, and saving it using the same name in other directory is a common requirement, in my humble opinion. – Tengerye Apr 14 '20 at 01:20
2

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') 
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
-2

you can concatenate the fileName string with a string that only specifies the extension while calling the function.

FrenchTechLead
  • 1,118
  • 3
  • 13
  • 20
  • 2
    as in `cv2.imwrite(filename + '.jpg', img)` ? Image would still be saved as `filename.jpg` right? And I would have to rename it again? – kampta May 03 '16 at 17:44
  • you can't convert an image from an extension to another simply by renaming the file, you have to whether chosing the extension when calling cv2.imwrite function or by doing this : img = cv.imread('1.png') cv.imwrite('01.jpg',img) as an example – FrenchTechLead May 03 '16 at 17:50
  • 1
    I don't want to convert image extensions/compression formats. I want to have an image filename without any extension, and want to specify compression format while writing the image to disk – kampta May 03 '16 at 18:34