How to specify OpenCV color type in Python

Problem

OpenCV has bindings for Python. Specifying the color type in calls to imread or imdecode gives this error:

$ cat foo.py
import cv
import cv2
mat = cv2.imread("foo.png", cv.CV_LOAD_IMAGE_ANYCOLOR)

$ python foo.py
AttributeError: 'module' object has no attribute 'CV_LOAD_IMAGE_ANYCOLOR'

Solution

It looks like the CV_LOAD_IMAGE enums which specify the color type of an image have not been exported to Python. Thankfully, the integer value of these enums can be passed directly to the call.

This enum is defined in highgui/highgui_c.h as:

enum
{
/* 8bit, color or not */
    CV_LOAD_IMAGE_UNCHANGED  =-1,
/* 8bit, gray */
    CV_LOAD_IMAGE_GRAYSCALE  =0,
/* ?, color */
    CV_LOAD_IMAGE_COLOR      =1,
/* any depth, ? */
    CV_LOAD_IMAGE_ANYDEPTH   =2,
/* ?, any color */
    CV_LOAD_IMAGE_ANYCOLOR   =4
};

Make the call using the integer value of the enum directly:

# To call with CV_LOAD_IMAGE_ANYCOLOR
mat = cv2.imread("foo.png", 4)

Tried with: OpenCV 2.4.9, Python 2.7.6 and Ubuntu 14.04

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s