Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python opencv imwrite ... can't find params

Tags:

python

opencv

I am using opencv with python. I wanted to do an cv2.imwrte:

cv2.imwrite('myimage.png', my_im)

The only problem is that opencv does not recognize the params constants:

cv2.imwrite('myimage.png', my_im, cv2.CV_IMWRITE_PNG_COMPRESSION, 0)

It cannot find CV_IMWRITE_PNG_COMPRESSION at all. Any ideas?

like image 998
ahmadh Avatar asked Mar 12 '12 03:03

ahmadh


2 Answers

I can't find key CV_XXXXX in the cv2 module:

  1. Try cv2.XXXXX
  2. Failing that, use cv2.cv.CV_XXXXX

In your case, cv2.cv.CV_IMWRITE_PNG_COMPRESSION.


More info.

The docs for OpenCV (cv2 interface) are a bit confusing.

Usually parameters that look like CV_XXXX are actually cv2.XXXX.

I use the following to search for the relevant cv2 constant name. Say I was looking for CV_MORPH_DILATE. I'll search for any constant with MORPH in it:

import cv2
nms = dir(cv2) # list of everything in the cv2 module
[m for m in nms if 'MORPH' in m]
# ['MORPH_BLACKHAT', 'MORPH_CLOSE', 'MORPH_CROSS', 'MORPH_DILATE',
#  'MORPH_ELLIPSE', 'MORPH_ERODE', 'MORPH_GRADIENT', 'MORPH_OPEN',
#  'MORPH_RECT', 'MORPH_TOPHAT']

From this I see that MORPH_DILATE is what I'm looking for.

However, sometimes the constants have not been moved from the cv interface to the cv2 interface yet.

In that case, you can find them under cv2.cv.CV_XXXX.

So, I looked for IMWRITE_PNG_COMPRESSION for you and couldn't find it (under cv2....), and so I looked under cv2.cv.CV_IMWRITE_PNG_COMPRESSION, and hey presto! It's there:

>>> cv2.cv.CV_IMWRITE_PNG_COMPRESSION
16
like image 60
mathematical.coffee Avatar answered Nov 04 '22 04:11

mathematical.coffee


Expanding on mathematical.coffee to ignore case and look in both namespaces:

import cv2
import cv2.cv as cv
nms  = [(n.lower(), n) for n in dir(cv)] # list of everything in the cv module
nms2 = [(n.lower(), n) for n in dir(cv2)] # list of everything in the cv2 module

search = 'imwrite'

print "in cv2\n ",[m[1] for m in nms2 if m[0].find(search.lower())>-1]
print "in cv\n ",[m[1] for m in nms if m[0].find(search.lower())>-1]

>>> 
in cv2
  ['imwrite']
in cv
  ['CV_IMWRITE_JPEG_QUALITY', 'CV_IMWRITE_PNG_COMPRESSION', 'CV_IMWRITE_PXM_BINARY']
>>>

Hopefully this problem will go away in some later release of cv2...

like image 3
Neon22 Avatar answered Nov 04 '22 02:11

Neon22