Package pyopencv :: Module interfaces
[hide private]
[frames] | no frames]

Source Code for Module pyopencv.interfaces

  1  #!/usr/bin/env python 
  2  # PyOpenCV - A Python wrapper for OpenCV 2.x using Boost.Python and NumPy 
  3   
  4  # Copyright (c) 2009, Minh-Tri Pham 
  5  # All rights reserved. 
  6   
  7  # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 
  8   
  9  #    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
 10  #    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 
 11  #    * Neither the name of pyopencv's copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 
 12   
 13  #THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 14   
 15  # For further inquiries, please contact Minh-Tri Pham at pmtri80@gmail.com. 
 16  # ---------------------------------------------------------------------------- 
 17   
 18   
 19  #============================================================================= 
 20  # Helpers for access to images for other GUI packages 
 21  #============================================================================= 
 22   
 23  from core import * 
 24  from core import _NP 
 25   
 26  __all__ = [] 
 27   
 28  #----------------------------------------------------------------------------- 
 29  # wx -- by Gary Bishop 
 30  #----------------------------------------------------------------------------- 
 31  # modified a bit by Minh-Tri Pham 
 32  try: 
 33      import wx 
 34   
35 - def cvIplImageAsBitmap(self):
36 """Converts a CV_8UC3 Mat into a wx.Bitmap 37 38 The Mat must be of type CV_8UC3, or else a TypeError is raised. 39 Since in gtk, a pixbuf's color space is RGB, it is assumed that the 40 Mat is also using this color space (i.e. you may want to call 41 cvCvtColor() to convert the color space *before* invoking this 42 function). Whether the image data is shared or copied to pixbuf 43 depends on how the function gtk.gdk.pixbuf_new_from_data() 44 handles the image data passed to it, and not on PyOpenCV. 45 """ 46 if self.type() != CV_8UC3: 47 raise TypeError('The source image is not of type CV_8UC3.') 48 return wx.BitmapFromBuffer(self.cols, self.rows, self.data)
49 50 Mat.to_wx_bitmap = cvIplImageAsBitmap 51 52 except ImportError: 53 pass 54 55 #----------------------------------------------------------------------------- 56 # PIL -- by Jeremy Bethmont 57 #----------------------------------------------------------------------------- 58 # modified by Minh-Tri Pham 59 try: 60 from PIL import Image 61 62 _cv_type_to_pil_mode_and_decoder = { 63 CV_8UC1: ("L", "L"), 64 CV_8UC3: ("RGB", "BGR"), 65 CV_8UC4: ("RGBA", "BGRA"), 66 CV_32SC1: ("I", "I"), 67 CV_32FC1: ("F", "F"), 68 } 69
70 - def _Mat_to_pil_image(self):
71 """Converts a Mat into a PIL Image 72 73 Right now, PyOpenCV can convert 1-channel (uint8|int32|float32) 74 Mats or uint8 (BGR|BGRA) Mats. Whether the image's data 75 array is shared or copied to PIL.Image depends on how PIL decodes 76 the array (i.e. via function PIL.Image.fromstring()). 77 """ 78 try: 79 mode, decoder = _cv_type_to_pil_mode_and_decoder[self.type()] 80 except KeyError: 81 raise TypeError("Don't know how to convert the image. Check its depth and/or its number of channels.") 82 return Image.fromstring(mode, (self.cols, self.rows), self.data, "raw", decoder, self.step, 1)
83 Mat.to_pil_image = _Mat_to_pil_image 84 85 _pil_image_bands_to_attrs = { 86 ('L',): ("uint8", 1, 1, "raw", "L"), 87 ('I',): ("int32", 4, 1, "raw", "I"), 88 ('F',): ("float32", 4, 1, "raw", "F"), 89 ('R', 'G', 'B'): ("uint8", 1, 3, "raw", "BGR"), 90 ('R', 'G', 'B', 'A'): ("uint8", 1, 4, "raw", "BGRA"), 91 } 92
93 - def cvCreateImageFromPilImage(pilimage):
94 """Converts a PIL.Image into an IplImage 95 96 Right now, PyOpenCV can convert PIL.Images of band ('L'), ('I'), 97 ('F'), ('R', 'G', 'B'), or ('R', 'G', 'B', 'A'). Whether the 98 data array is copied from PIL.Image to IplImage or shared between 99 the two images depends on how PIL converts the PIL.Image's data into 100 a string (i.e. via function PIL.Image.tostring()). 101 """ 102 try: 103 dtype, elem_size, nchannels, decoder, mode = _pil_image_bands_to_attrs[pilimage.getbands()] 104 except KeyError: 105 raise TypeError("Don't know how to convert the image. Check its bands and/or its mode.") 106 cols = pilimage.size[0] 107 rows = pilimage.size[1] 108 step = cols * nchannels * elem_size 109 data = pilimage.tostring(decoder, mode, step) 110 z = _NP.frombuffer(data, dtype=dtype, count=rows*cols*nchannels).reshape(rows, cols, nchannels) 111 return Mat.from_ndarray(z)
112 113 Mat.from_pil_image = staticmethod(cvCreateImageFromPilImage) 114 115 except ImportError: 116 pass 117 118 119 #----------------------------------------------------------------------------- 120 # GTK's pixbuf -- by Daniel Carvalho 121 #----------------------------------------------------------------------------- 122 # modified by Minh-Tri Pham 123 try: 124 import pygtk 125 pygtk.require20() 126 import gtk 127
128 - def _mat_as_gtk_pixbuf(self):
129 """Converts a CV_8UC3 Mat into a gtk.gdk.pixbuf 130 131 The Mat must be of type CV_8UC3, or else a TypeError is raised. 132 Since in gtk, a pixbuf's color space is RGB, it is assumed that the 133 Mat is also using this color space (i.e. you may want to call 134 cvCvtColor() to convert the color space *before* invoking this 135 function). Whether the image data is shared or copied to pixbuf 136 depends on how the function gtk.gdk.pixbuf_new_from_data() 137 handles the image data passed to it, and not on PyOpenCV. 138 """ 139 if self.type() != CV_8UC3: 140 raise TypeError('The source image is not of type CV_8UC3.') 141 142 return gtk.gdk.pixbuf_new_from_data(self.data, gtk.gdk.COLORSPACE_RGB, 143 False, 8, self.cols, self.rows, self.step)
144 145 Mat.to_gtk_pixbuf = _mat_as_gtk_pixbuf 146
147 - def cvCreateMatFromGtkPixbuf(pixbuf):
148 """Converts a gtk.gdk.pixbuf into a CV_8UC3 Mat 149 150 The pixbuf must have 8 bits per sample and no alpha channel, or else 151 a TypeError is raised. Since in gtk, a pixbuf's color space is RGB, 152 the output Mat would therefore use the same color space (i.e. you 153 may want to call cvCvtColor() to convert the color space *after* 154 invoking this function). Whether the pixbuf's data is shared or 155 copied to the Mat depends on whether the function 156 gtk.gdk.get_pixels() returns its data array or a copy of the array, 157 and not on PyOpenCV. 158 """ 159 if not isinstance(pixbuf, gtk.gdk.Pixbuf): 160 raise TypeError("The first argument 'pixbuf' is not a gtk pixbuf.") 161 if pixbuf.get_has_alpha(): 162 raise TypeError('Pixbuf source with an alpha channel is currently not supported.') 163 if pixbuf.get_bits_per_sample() != 8: 164 raise TypeError('The pixbuf source does not have exactly 8 bits per sample.') 165 166 rows = pixbuf.get_height() 167 cols = pixbuf.get_width() 168 step = pixbuf.get_row_stride() 169 z = _NP.frombuffer(pixbuf.get_pixels(), dtype='uint8', count=rows*step).reshape(rows, step, 1) 170 z.shape = (rows, cols, 3) 171 z.strides = (step, 3, 1) 172 return Mat.from_ndarray(z)
173 174 Mat.from_gtk_pixbuf = staticmethod(cvCreateMatFromGtkPixbuf) 175 176 except ImportError: 177 pass 178 except AssertionError: 179 pass 180