1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 __all__ = ['fromIplImage','fromCvMat','datapath']
26
27
28 from os.path import dirname, join
29 from numpy import frombuffer, dtype
30 from ctypes import POINTER
31 from pycv.interfaces.opencv import IplImage, cvImageAsBuffer, IPL_DEPTH_1U, \
32 IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16U, IPL_DEPTH_16S, IPL_DEPTH_32S, \
33 IPL_DEPTH_32F, IPL_DEPTH_64F, CvMat, CV_8U, CV_8S, CV_16U, CV_16S, \
34 CV_32S, CV_32F, CV_64F, CV_CN_SHIFT, cvCvMatAsBuffer
35
36
37 datapath = join(dirname(__file__), 'data')
38
39 _dict_opencvdepth2dtype = {
40 IPL_DEPTH_1U: 'bool',
41 IPL_DEPTH_8U: 'uint8',
42 IPL_DEPTH_8S: 'int8',
43 IPL_DEPTH_16U: 'uint16',
44 IPL_DEPTH_16S: 'int16',
45 IPL_DEPTH_32S: 'int32',
46 IPL_DEPTH_32F: 'float32',
47 IPL_DEPTH_64F: 'float64',
48 }
49
51 """Convert a POINTER(IplImage) into numpy.array
52
53 Input:
54 img: a POINTER(IplImage)
55 Output:
56 img2: a numpy.array
57 """
58 if not isinstance(img,POINTER(IplImage)):
59 raise TypeError('img is not of type POINTER(IplImage)')
60
61 dtypename = _dict_opencvdepth2dtype[img.contents.depth]
62 data = frombuffer(cvImageAsBuffer(img),dtype=dtypename)
63
64 w = img.contents.width
65 ws = img.contents.widthStep / dtype(dtypename).itemsize
66 h = img.contents.height
67 nc = img.contents.nChannels
68
69 if nc > 1:
70 return data.reshape(h,ws)[:,:w*nc].reshape(h,w,nc)
71 else:
72 return data.reshape(h,ws)[:,:w]
73
74 _dict_opencvmat2dtype = {
75 CV_8U: 'uint8',
76 CV_8S: 'int8',
77 CV_16U: 'uint16',
78 CV_16S: 'int16',
79 CV_32S: 'int32',
80 CV_32F: 'float32',
81 CV_64F: 'float64',
82 }
83
85 """Convert a POINTER(CvMat) into numpy.array
86
87 Input:
88 mat: a POINTER(CvMat)
89 Output:
90 mat2: a numpy.array
91 """
92 if not isinstance(mat,POINTER(CvMat)):
93 raise TypeError('mat is not of type POINTER(CvMat)')
94
95 typedepth = mat[0].type & 0x0FFF
96 thetype = typedepth & ((1 << CV_CN_SHIFT)-1)
97 nc = (typedepth >> CV_CN_SHIFT) + 1
98 dtypename = _dict_opencvmat2dtype[thetype]
99 data = frombuffer(cvCvMatAsBuffer(mat),dtype=dtypename)
100
101 w = mat[0].cols
102 ws = mat[0].step / dtype(dtypename).itemsize
103 h = mat[0].rows
104
105 if nc > 1:
106 return data.reshape(h,ws)[:,:w*nc].reshape(h,w,nc)
107 else:
108 return data.reshape(h,ws)[:,:w]
109