Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to specify OpenCV color type in Python

📅 2015-Jan-23 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ enum, error, opencv, python ⬩ 📚 Archive

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


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧