|
| 1 | +import numpy as np |
| 2 | +from libc.string cimport memcpy |
| 3 | + |
| 4 | +def nptype2cvtype(npty, nch): |
| 5 | + if npty == np.uint8: |
| 6 | + r = CV_8U |
| 7 | + elif npty == np.int8: |
| 8 | + r = CV_8S |
| 9 | + elif npty == np.uint16: |
| 10 | + r = CV_16U |
| 11 | + elif npty == np.int16: |
| 12 | + r = CV_16S |
| 13 | + elif npty == np.int32: |
| 14 | + r = CV_32S |
| 15 | + elif npty == np.float32: |
| 16 | + r = CV_32F |
| 17 | + elif npty == np.float64: |
| 18 | + r = CV_64F |
| 19 | + |
| 20 | + return CV_MAKETYPE(r, nch) |
| 21 | + |
| 22 | +def cvtype2nptype(cvty): |
| 23 | + d = CV_MAT_DEPTH(cvty) |
| 24 | + nch = CV_MAT_CN(cvty) |
| 25 | + |
| 26 | + if d == CV_8U: |
| 27 | + r = np.uint8 |
| 28 | + elif d == CV_8S: |
| 29 | + r = np.int8 |
| 30 | + elif d == CV_16U: |
| 31 | + r = np.uint16 |
| 32 | + elif d == CV_16S: |
| 33 | + r = np.int16 |
| 34 | + elif d == CV_32S: |
| 35 | + r = np.int32 |
| 36 | + elif d == CV_32F: |
| 37 | + r = np.float32 |
| 38 | + elif d == CV_64F: |
| 39 | + r = np.float64 |
| 40 | + return [r, nch] |
| 41 | + |
| 42 | +cdef Mat nparray2cvmat(np.ndarray ary): |
| 43 | + if ary.ndim==3 and ary.shape[2]==1: |
| 44 | + ary = ary.reshape(ary.shape[0], ary.shape[1]) |
| 45 | + |
| 46 | + cdef int r = ary.shape[0] |
| 47 | + cdef int c = ary.shape[1] |
| 48 | + |
| 49 | + if ary.ndim == 2: |
| 50 | + nch = 1 |
| 51 | + else: |
| 52 | + nch = ary.shape[2] |
| 53 | + |
| 54 | + if not ary.flags['C_CONTIGUOUS']: |
| 55 | + ary = np.ascontiguousarray(ary, dtype=ary.dtype) |
| 56 | + #cdef Mat outmat = Mat(r, c, nptype2cvtype(ary.dtype,nch)) |
| 57 | + #memcpy(outmat.data, ary.data, ary.nbytes) |
| 58 | + cdef Mat outmat = Mat(r, c, nptype2cvtype(ary.dtype,nch), ary.data, 0) #memoryview |
| 59 | + return outmat |
| 60 | + |
| 61 | +cdef np.ndarray cvmat2nparray(Mat &inmat): |
| 62 | + [ty, nch] = cvtype2nptype(inmat.type()) |
| 63 | + |
| 64 | + if nch == 1: |
| 65 | + dim = (inmat.rows, inmat.cols) |
| 66 | + else: |
| 67 | + dim = (inmat.rows, inmat.cols, nch) |
| 68 | + |
| 69 | + cdef np.ndarray ary = np.empty(dim, dtype=ty) |
| 70 | + memcpy(ary.data, inmat.data, ary.nbytes) |
| 71 | + return ary |
| 72 | + |
| 73 | +cdef inline Rect pylist2cvrect(list rectlist): |
| 74 | + cdef Rect rect = Rect(rectlist[0], rectlist[1], rectlist[2], rectlist[3]) |
| 75 | + return rect |
| 76 | + |
| 77 | +cdef inline list cvrect2pylist(Rect &rect): |
| 78 | + return [rect.x, rect.y, rect.width, rect.height] |
0 commit comments