Update the trunk to the OpenCV's CVS (2008-07-14)
[opencv] / interfaces / swig / python / adaptors.py
1 #########################################################################################
2 #
3 #  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 #
5 #  By downloading, copying, installing or using the software you agree to this license.
6 #  If you do not agree to this license, do not download, install,
7 #  copy or use the software.
8 #
9 #
10 #                        Intel License Agreement
11 #                For Open Source Computer Vision Library
12 #
13 # Copyright (C) 2000, Intel Corporation, all rights reserved.
14 # Third party copyrights are property of their respective owners.
15 #
16 # Redistribution and use in source and binary forms, with or without modification,
17 # are permitted provided that the following conditions are met:
18 #
19 #   * Redistribution's of source code must retain the above copyright notice,
20 #     this list of conditions and the following disclaimer.
21 #
22 #   * Redistribution's in binary form must reproduce the above copyright notice,
23 #     this list of conditions and the following disclaimer in the documentation
24 #     and/or other materials provided with the distribution.
25 #
26 #   * The name of Intel Corporation may not be used to endorse or promote products
27 #     derived from this software without specific prior written permission.
28 #
29 # This software is provided by the copyright holders and contributors "as is" and
30 # any express or implied warranties, including, but not limited to, the implied
31 # warranties of merchantability and fitness for a particular purpose are disclaimed.
32 # In no event shall the Intel Corporation or contributors be liable for any direct,
33 # indirect, incidental, special, exemplary, or consequential damages
34 # (including, but not limited to, procurement of substitute goods or services;
35 # loss of use, data, or profits; or business interruption) however caused
36 # and on any theory of liability, whether in contract, strict liability,
37 # or tort (including negligence or otherwise) arising in any way out of
38 # the use of this software, even if advised of the possibility of such damage.
39 #
40 #########################################################################################
41
42
43 # 2004-03-16, Mark Asbach <asbach@ient.rwth-aachen.de>
44 #             Institute of Communications Engineering, RWTH Aachen University
45 # 2007-02-xx, direct interface to numpy by Vicent Mas <vmas@carabos.com>
46 #             Carabos Coop. V.
47 # 2007-10-08, try/catch 
48
49 """Adaptors to interchange data with numpy and/or PIL
50
51 This module provides explicit conversion of OpenCV images/matrices to and from
52 the Python Imaging Library (PIL) and python's newest numeric library (numpy).
53
54 Currently supported image/matrix formats are:
55     - 3 x  8 bit  RGB (GBR)
56     - 1 x  8 bit  Grayscale
57     - 1 x 32 bit  Float
58
59 In numpy, images are represented as multidimensional arrays with
60 a third dimension representing the image channels if more than one
61 channel is present.
62 """
63
64 import cv
65
66 try:
67   import PIL.Image
68
69   ###########################################################################
70   def Ipl2PIL(input):
71       """Converts an OpenCV/IPL image to PIL the Python Imaging Library.
72   
73       Supported input image formats are
74          IPL_DEPTH_8U  x 1 channel
75          IPL_DEPTH_8U  x 3 channels
76          IPL_DEPTH_32F x 1 channel
77       """
78   
79       if not isinstance(input, cv.CvMat):
80           raise TypeError, 'must be called with a cv.CvMat!'
81   
82       # assert that the channels are interleaved
83       if input.dataOrder != 0:
84           raise ValueError, 'dataOrder must be 0 (interleaved)!'
85   
86       #orientation
87       if input.origin == 0:
88           orientation = 1 # top left
89       elif input.origin == 1:
90           orientation = -1 # bottom left
91       else:
92           raise ValueError, 'origin must be 0 or 1!'
93   
94       # mode dictionary:
95       # (channels, depth) : (source mode, dest mode, depth in byte)
96       mode_list = {
97           (1, cv.IPL_DEPTH_8U)  : ("L", "L", 1),
98           (3, cv.IPL_DEPTH_8U)  : ("BGR", "RGB", 3),
99           (1, cv.IPL_DEPTH_32F) : ("F", "F", 4)
100           }
101   
102       key = (input.nChannels, input.depth)
103       if not mode_list.has_key(key):
104           raise ValueError, 'unknown or unsupported input mode'
105   
106       modes = mode_list[key]
107   
108       return PIL.Image.fromstring(
109           modes[1], # mode
110           (input.width, input.height), # size tuple
111           input.imageData, # data
112           "raw",
113           modes[0], # raw mode
114           input.widthStep, # stride
115           orientation # orientation
116           )
117   
118   
119   ###########################################################################
120   def PIL2Ipl(input):
121       """Converts a PIL image to the OpenCV/IPL CvMat data format.
122   
123       Supported input image formats are:
124           RGB
125           L
126           F
127       """
128   
129       if not (isinstance(input, PIL.Image.Image)):
130           raise TypeError, 'Must be called with PIL.Image.Image!'
131       
132       # mode dictionary:
133       # (pil_mode : (ipl_depth, ipl_channels)
134       mode_list = {
135           "RGB" : (cv.IPL_DEPTH_8U, 3),
136           "L"   : (cv.IPL_DEPTH_8U, 1),
137           "F"   : (cv.IPL_DEPTH_32F, 1)
138           }
139       
140       if not mode_list.has_key(input.mode):
141           raise ValueError, 'unknown or unsupported input mode'
142       
143       result = cv.cvCreateImage(
144           cv.cvSize(input.size[0], input.size[1]),  # size
145           mode_list[input.mode][0],  # depth
146           mode_list[input.mode][1]  # channels
147           )
148   
149       # set imageData
150       result.imageData = input.tostring()
151       return result
152
153 except ImportError:
154   pass
155
156
157 #############################################################################
158 #############################################################################
159
160 try:
161   
162   import numpy
163   
164   
165   ###########################################################################
166   def NumPy2Ipl(input):
167       """Converts a numpy array to the OpenCV/IPL CvMat data format.
168   
169       Supported input array layouts:
170          2 dimensions of numpy.uint8
171          3 dimensions of numpy.uint8
172          2 dimensions of numpy.float32
173          2 dimensions of numpy.float64
174       """
175       
176       if not isinstance(input, numpy.ndarray):
177           raise TypeError, 'Must be called with numpy.ndarray!'
178   
179       # Check the number of dimensions of the input array
180       ndim = input.ndim
181       if not ndim in (2, 3):
182           raise ValueError, 'Only 2D-arrays and 3D-arrays are supported!'
183       
184       # Get the number of channels
185       if ndim == 2:
186           channels = 1
187       else:
188           channels = input.shape[2]
189       
190       # Get the image depth
191       if input.dtype == numpy.uint8:
192           depth = cv.IPL_DEPTH_8U
193       elif input.dtype == numpy.float32:
194           depth = cv.IPL_DEPTH_32F
195       elif input.dtype == numpy.float64:
196           depth = cv.IPL_DEPTH_64F
197       
198       # supported modes list: [(channels, dtype), ...]
199       modes_list = [(1, numpy.uint8), (3, numpy.uint8), (1, numpy.float32), (1, numpy.float64)]
200       
201       # Check if the input array layout is supported
202       if not (channels, input.dtype) in modes_list:
203           raise ValueError, 'Unknown or unsupported input mode'
204       
205       result = cv.cvCreateImage(
206           cv.cvSize(input.shape[1], input.shape[0]),  # size
207           depth,  # depth
208           channels  # channels
209           )
210       
211       # set imageData
212       result.imageData = input.tostring()
213       
214       return result
215   
216   
217   ###########################################################################
218   def Ipl2NumPy(input):
219       """Converts an OpenCV/IPL image to a numpy array.
220   
221       Supported input image formats are
222          IPL_DEPTH_8U  x 1 channel
223          IPL_DEPTH_8U  x 3 channels
224          IPL_DEPTH_32F x 1 channel
225          IPL_DEPTH_64F x 1 channel
226       """
227   
228       if not isinstance(input, cv.CvMat):
229           raise TypeError, 'must be called with a cv.CvMat!'
230   
231       # assert that the channels are interleaved
232       if input.dataOrder != 0:
233           raise ValueError, 'dataOrder must be 0 (interleaved)!'
234   
235       # data type dictionary:
236       # (channels, depth) : numpy dtype
237       ipl2dtype = {
238           (1, cv.IPL_DEPTH_8U)  : numpy.uint8,
239           (3, cv.IPL_DEPTH_8U)  : numpy.uint8,
240           (1, cv.IPL_DEPTH_32F) : numpy.float32,
241           (1, cv.IPL_DEPTH_64F) : numpy.float64
242           }
243   
244       key = (input.nChannels, input.depth)
245       if not ipl2dtype.has_key(key):
246           raise ValueError, 'unknown or unsupported input mode'
247   
248       # Get the numpy array and reshape it correctly
249       if input.nChannels == 1:
250           array_1d = numpy.fromstring(input.imageData, dtype=ipl2dtype[key])
251           return numpy.reshape(array_1d, (input.height, input.width))
252       elif input.nChannels == 3:
253           # Change the order of channels from BGR to RGB
254           rgb = cv.cvCreateImage(cv.cvSize(input.width, input.height), input.depth, 3)
255           cv.cvCvtColor(input, rgb, cv.CV_BGR2RGB)
256           array_1d = numpy.fromstring(rgb.imageData, dtype=ipl2dtype[key])
257           return numpy.reshape(array_1d, (input.height, input.width, 3))
258
259 except ImportError:
260   pass
261
262
263 ###########################################################################
264 ###########################################################################
265
266
267 try:
268
269   import PIL.Image
270   import numpy
271
272   ###########################################################################
273   def PIL2NumPy(input):
274       """THIS METHOD IS DEPRECATED
275       
276       Converts a PIL image to a numpy array.
277   
278       Supported input image formats are:
279           RGB
280           L
281           F
282       """
283   
284       if not (isinstance(input, PIL.Image.Image)):
285           raise TypeError, 'Must be called with PIL.Image.Image!'
286   
287       # modes dictionary:
288       # pil_mode : numpy dtype
289       modes_map = {
290           "RGB" : numpy.uint8,
291           "L"   : numpy.uint8,
292           "F"   : numpy.float32
293           }
294   
295       if not modes_map.has_key(input.mode):
296           raise ValueError, 'Unknown or unsupported input mode!. Supported modes are RGB, L and F.'
297   
298       result_ro = numpy.asarray(input, dtype=modes_map[input.mode])  # Read-only array
299       return result_ro.copy()  # Return a writeable array
300   
301   
302   ###########################################################################
303   def NumPy2PIL(input):
304       """THIS METHOD IS DEPRECATED
305       
306       Converts a numpy array to a PIL image.
307   
308       Supported input array layouts:
309          2 dimensions of numpy.uint8
310          3 dimensions of numpy.uint8
311          2 dimensions of numpy.float32
312       """
313   
314       if not isinstance(input, numpy.ndarray):
315           raise TypeError, 'Must be called with numpy.ndarray!'
316   
317       # Check the number of dimensions of the input array
318       ndim = input.ndim
319       if not ndim in (2, 3):
320           raise ValueError, 'Only 2D-arrays and 3D-arrays are supported!'
321   
322       if ndim == 2:
323           channels = 1
324       else:
325           channels = input.shape[2]
326   
327       # supported modes list: [(channels, dtype), ...]
328       modes_list = [(1, numpy.uint8), (3, numpy.uint8), (1, numpy.float32)]
329   
330       mode = (channels, input.dtype)
331       if not mode in modes_list:
332           raise ValueError, 'Unknown or unsupported input mode'
333   
334       return PIL.Image.fromarray(input)
335
336 except ImportError:
337   pass