Move the sources to trunk
[opencv] / interfaces / swig / python / matlab_syntax.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 """Matlab syntax for OpenCV
43
44 For those who have switched from Matlab, this module offers similar syntax to the basic
45 Matlab commands. I.e. you can invoke 'imread' to load images, 'imshow', etc.
46 """
47
48 from cv import *
49 from highgui import cvShowImage,cvNamedWindow,cvLoadImage,cvWaitKey 
50
51 #__all__ = ['imagesc', 'display', 'imread', 'imshow', 'saveimage', 'loadimage', 'pause',
52 #           'Image', 'Image8', 'Image8c3', 'Image32s', 'Image32f', 'Image64f']
53
54 def eye(*args):
55     mat = array(*args)
56     cvSetIdentity(mat);
57     return mat
58
59 def ones(*args):
60     mat = array(*args)
61     cvSet(mat, cvScalarAll(1.0))
62     return mat
63
64 def zeros(*args):
65     mat = array(*args)
66     cvSet(mat, cvScalarAll(0.0))
67     return mat
68
69 def array(*args):
70     m=1
71     n=1
72     c=1
73     classname='single'
74     nargs = len(args)
75     # nasty argument parsing
76     if nargs>0:
77         if isinstance(args[0],tuple) or isinstance(args[0],list) and len(args[0]) > 1:
78             m=args[0][0]
79             n=args[0][1]
80             if len(args[0])>2:
81                 c=args[0][2]
82             if len(args)>1:
83                 classname = args[1]
84         else:
85             m=args[0]
86             if nargs == 1:
87                 n=args[0]
88             elif nargs > 1:
89                 # is the last argument the classname?
90                 if args[nargs-1].__class__ == str:
91                     classname = args[nargs-1]
92                     nargs-=1
93                 if nargs > 1:
94                     n = args[1]
95                 if nargs > 2:
96                     c = args[2]
97
98     if(classname=='double'):
99         depth=cv.CV_64F 
100     elif(classname=='single'):
101         depth=cv.CV_32F
102     elif(classname=='int8'):
103         depth=cv.CV_8S
104     elif(classname=='uint8'):
105         depth=cv.CV_8U
106     elif(classname=='int16'):
107         depth=cv.CV_16S
108     elif(classname=='uint16'):
109         depth=cv.CV_16U
110     elif(classname=='int32' or classname=='uint32' or 
111             classname=='int64' or classname=='uint64'):
112         depth=cv.CV_32S
113     else:
114         depth=cv.CV_32F
115     depth = CV_MAKETYPE(depth, c)
116     return cvCreateMat(m,n,depth)
117  
118 def size(X,dim=-1):
119     # CvMat
120     if hasattr(X, "type"):
121         sz = (X.rows, X.cols, CV_MAT_CN(X.type))
122     # IplImage
123     elif hasattr(X, "nChannels"):
124         sz = (X.height, X.width, X.nChannels)
125     # CvMatNd
126     else:
127         sz = cvGetDims(X)
128
129     if dim is -1:
130         return sz
131     return sz[dim]
132
133 def reshape(X, m, n=1, c=-1):
134     '''
135     reshape will produce different results in matlab and python due to the
136     order of elements stored in the array (row-major vs. column major)
137     '''
138     if c==-1:
139         c = CV_MAT_CN(X)
140     return cvReshape(X, c, m)
141      
142
143 def im2float(im):
144     mat = cvGetMat(im);
145     if CV_MAT_DEPTH(mat.type)==CV_32F:
146         return mat
147     
148     im64f = array(size(im), 'float')
149     cvConvertScale(im, im64f, 1.0, 0.0)
150     return im64f
151
152 def im2double(im):
153     mat = cvGetMat(im);
154     if CV_MAT_DEPTH(mat.type)==CV_64F:
155         return mat
156     im64f = array(size(im), 'double')
157     cvConvertScale(im, im64f, 1.0, 0.0)
158     return im64f
159
160 def rgb2ntsc (rgb):
161     trans = [ [0.299,  0.596,  0.211], [0.587, -0.274, -0.523], [0.114, -0.322,  0.312] ];
162     return rgb * trans;
163     
164 def rgb2gray(rgb):
165     ntscmap = rgb2ntsc (rgb);
166     graymap = ntscmap [:, 1] * ones (1, 3);
167     return graymap
168
169 class cvImageViewer:
170     """
171     Wrapper class for some matlab/octave/scilab syntax image viewing functions
172     """
173     currentWindowName = ""
174     currentWindow = -1
175     maxWindow = -1
176
177     def imagesc(self,im, clims=None):
178         """
179         Display a normalized version of the image
180         """
181         if(self.currentWindow==-1):
182             self.display()
183
184         # don't normalize multichannel image
185         #if(im.nChannels>1):
186         #    if(im.depth!=cv.IPL_DEPTH_8U):
187         #        im2 = cvCreateImage( cvSize(im.width, im.height), cv.IPL_DEPTH_8U, im.nChannels)
188         #        cvScale(im, im2)
189         #        im = im2
190         #    cvShowImage(self.currentWindowName, im)
191         #    return self.currentWindow
192         
193         # normalize image
194         if clims:
195             [minv, maxv] = clims
196         else:
197             [minv,maxv] = cvMinMaxLoc(im)
198         if maxv != minv:
199             s = 255.0/(maxv-minv)
200             shift =  255*(-minv)/(maxv-minv)
201         else:
202             s = 1.0
203             shift = -maxv
204
205         im2 = array( size(im), 'uint8' )
206         cvConvertScale(im, im2, s, shift)
207         
208         cvShowImage(self.currentWindowName, im2)
209
210     def image(self, im):
211         """
212         Display image as is -- probably not what you'd expect for FP or integer images
213         """
214         if(self.currentWindow==-1):
215             self.display()
216
217         cvShowImage(self.currentWindowName,im)
218         return self.currentWindow
219         
220     
221     def display(self, index=-1):
222         """
223         open a new window
224         """
225         if(index==-1):
226             self.maxWindow = self.maxWindow+1;
227             index= self.maxWindow;
228
229         if(index > self.maxWindow):
230             self.maxWindow = index;
231
232         self.currentWindow = index;
233         self.currentWindowName = "opencv-python window %d" % self.currentWindow
234         cvNamedWindow(self.currentWindowName,0)
235         return self.currentWindow
236
237 def drawnow():
238     cvWaitKey(10)
239
240 def pause(delay=-1):
241     if delay<0:
242         cvWaitKey(-1)
243     else:
244         cvWaitKey(delay*1000)
245
246 c = cvImageViewer()
247 imagesc = c.imagesc
248 display = c.display
249 image = c.image
250 imshow = c.image
251
252 def imread(fname):
253     return cvLoadImage(fname, -1)   
254 loadimage = imread
255 imload = imread
256
257 def imsave(im, fname, format):
258     return cvSaveImage(fname, im)
259 saveimage = imsave
260
261 def gradient(F):
262     F = im2float(F)
263     Fx = array(size(F))
264     Fy = array(size(F))
265     
266     # new images
267     cvSobel(F, Fx, 1, 0, CV_SCHARR)
268     cvSobel(F, Fy, 0, 1, CV_SCHARR)
269     return (Fx, Fy)