1 #########################################################################################
3 # IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
10 # Intel License Agreement
11 # For Open Source Computer Vision Library
13 # Copyright (C) 2000, Intel Corporation, all rights reserved.
14 # Third party copyrights are property of their respective owners.
16 # Redistribution and use in source and binary forms, with or without modification,
17 # are permitted provided that the following conditions are met:
19 # * Redistribution's of source code must retain the above copyright notice,
20 # this list of conditions and the following disclaimer.
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.
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.
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.
40 #########################################################################################
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>
47 # 2007-10-08, try/catch
49 """Adaptors to interchange data with numpy and/or PIL
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).
54 Currently supported image/matrix formats are:
59 In numpy, images are represented as multidimensional arrays with
60 a third dimension representing the image channels if more than one
69 ###########################################################################
71 """Converts an OpenCV/IPL image to PIL the Python Imaging Library.
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
79 if not isinstance(input, cv.CvMat):
80 raise TypeError, 'must be called with a cv.CvMat!'
82 # assert that the channels are interleaved
83 if input.dataOrder != 0:
84 raise ValueError, 'dataOrder must be 0 (interleaved)!'
88 orientation = 1 # top left
89 elif input.origin == 1:
90 orientation = -1 # bottom left
92 raise ValueError, 'origin must be 0 or 1!'
95 # (channels, depth) : (source mode, dest mode, depth in byte)
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)
102 key = (input.nChannels, input.depth)
103 if not mode_list.has_key(key):
104 raise ValueError, 'unknown or unsupported input mode'
106 modes = mode_list[key]
108 return PIL.Image.fromstring(
110 (input.width, input.height), # size tuple
111 input.imageData, # data
114 input.widthStep, # stride
115 orientation # orientation
119 ###########################################################################
121 """Converts a PIL image to the OpenCV/IPL CvMat data format.
123 Supported input image formats are:
129 if not (isinstance(input, PIL.Image.Image)):
130 raise TypeError, 'Must be called with PIL.Image.Image!'
133 # (pil_mode : (ipl_depth, ipl_channels)
135 "RGB" : (cv.IPL_DEPTH_8U, 3),
136 "L" : (cv.IPL_DEPTH_8U, 1),
137 "F" : (cv.IPL_DEPTH_32F, 1)
140 if not mode_list.has_key(input.mode):
141 raise ValueError, 'unknown or unsupported input mode'
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
150 result.imageData = input.tostring()
157 #############################################################################
158 #############################################################################
165 ###########################################################################
166 def NumPy2Ipl(input):
167 """Converts a numpy array to the OpenCV/IPL CvMat data format.
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
176 if not isinstance(input, numpy.ndarray):
177 raise TypeError, 'Must be called with numpy.ndarray!'
179 # Check the number of dimensions of the input array
181 if not ndim in (2, 3):
182 raise ValueError, 'Only 2D-arrays and 3D-arrays are supported!'
184 # Get the number of channels
188 channels = input.shape[2]
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
198 # supported modes list: [(channels, dtype), ...]
199 modes_list = [(1, numpy.uint8), (3, numpy.uint8), (1, numpy.float32), (1, numpy.float64)]
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'
205 result = cv.cvCreateImage(
206 cv.cvSize(input.shape[1], input.shape[0]), # size
212 result.imageData = input.tostring()
217 ###########################################################################
218 def Ipl2NumPy(input):
219 """Converts an OpenCV/IPL image to a numpy array.
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
228 if not isinstance(input, cv.CvMat):
229 raise TypeError, 'must be called with a cv.CvMat!'
231 # assert that the channels are interleaved
232 if input.dataOrder != 0:
233 raise ValueError, 'dataOrder must be 0 (interleaved)!'
235 # data type dictionary:
236 # (channels, depth) : numpy dtype
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
244 key = (input.nChannels, input.depth)
245 if not ipl2dtype.has_key(key):
246 raise ValueError, 'unknown or unsupported input mode'
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))
263 ###########################################################################
264 ###########################################################################
272 ###########################################################################
273 def PIL2NumPy(input):
274 """THIS METHOD IS DEPRECATED
276 Converts a PIL image to a numpy array.
278 Supported input image formats are:
284 if not (isinstance(input, PIL.Image.Image)):
285 raise TypeError, 'Must be called with PIL.Image.Image!'
288 # pil_mode : numpy dtype
295 if not modes_map.has_key(input.mode):
296 raise ValueError, 'Unknown or unsupported input mode!. Supported modes are RGB, L and F.'
298 result_ro = numpy.asarray(input, dtype=modes_map[input.mode]) # Read-only array
299 return result_ro.copy() # Return a writeable array
302 ###########################################################################
303 def NumPy2PIL(input):
304 """THIS METHOD IS DEPRECATED
306 Converts a numpy array to a PIL image.
308 Supported input array layouts:
309 2 dimensions of numpy.uint8
310 3 dimensions of numpy.uint8
311 2 dimensions of numpy.float32
314 if not isinstance(input, numpy.ndarray):
315 raise TypeError, 'Must be called with numpy.ndarray!'
317 # Check the number of dimensions of the input array
319 if not ndim in (2, 3):
320 raise ValueError, 'Only 2D-arrays and 3D-arrays are supported!'
325 channels = input.shape[2]
327 # supported modes list: [(channels, dtype), ...]
328 modes_list = [(1, numpy.uint8), (3, numpy.uint8), (1, numpy.float32)]
330 mode = (channels, input.dtype)
331 if not mode in modes_list:
332 raise ValueError, 'Unknown or unsupported input mode'
334 return PIL.Image.fromarray(input)