Ask Your Question

Revision history [back]

Python documentation is a little patchy, but in my opinion worth persisting with. Sometimes the C++ description is very helpful as it says the type of array required.

The main problem with your code examples is that OpenCV Python functions which process images take as input Numpy arrays. This means you have to read the image from .jpg into an array, and then pass it to the function. The result from cvtColor is another Numpy array.

Example:

import numpy as np
import cv2
im=cv2.imread('c:/temp/i1.jpg',cv2.cv.CV_LOAD_IMAGE_COLOR)
type(im)  #Shows Numpy array
im.shape #Numpy array object shape gives image size
cv2.imshow('Colour',im)
im_gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray',im_gray)  #show image on screen
cv2.imwrite('c:/temp/i1g.jpg',im_gray)  #write to file
im_gray[...]=0  #Use Numpy broadcasting
cv2.imshow('Turned black',im_gray)

If you unpack the OpenCV source there is a directory of samples called opencv\samples\python2 These are all using the cv2 interface.