forked from maktu6/PyPatchMatch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatchmatch_inpaint.pyx
More file actions
92 lines (70 loc) · 2.6 KB
/
patchmatch_inpaint.pyx
File metadata and controls
92 lines (70 loc) · 2.6 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import numpy as np
cimport numpy as np # for np.ndarray
from libc.string cimport memcpy
from patchmatch_inpaint cimport *
# inspired and adapted from http://makerwannabe.blogspot.ch/2013/09/calling-opencv-functions-via-cython.html
cdef Mat np2Mat3D(np.ndarray ary):
assert ary.ndim==3 and ary.shape[2]==3, "ASSERT::3channel RGB only!!"
ary = np.dstack((ary[...,2], ary[...,1], ary[...,0])) #RGB -> BGR
cdef np.ndarray[np.uint8_t, ndim=3, mode ='c'] np_buff = np.ascontiguousarray(ary, dtype=np.uint8)
cdef unsigned int* im_buff = <unsigned int*> np_buff.data
cdef int r = ary.shape[0]
cdef int c = ary.shape[1]
cdef Mat m
m.create(r, c, CV_8UC3)
memcpy(m.data, im_buff, r*c*3)
return m
cdef Mat np2Mat2D(np.ndarray ary):
assert ary.ndim==2 , "ASSERT::1 channel grayscale only!!"
cdef np.ndarray[np.uint8_t, ndim=2, mode ='c'] np_buff = np.ascontiguousarray(ary, dtype=np.uint8)
cdef unsigned int* im_buff = <unsigned int*> np_buff.data
cdef int r = ary.shape[0]
cdef int c = ary.shape[1]
cdef Mat m
m.create(r, c, CV_8UC1)
memcpy(m.data, im_buff, r*c)
return m
cdef Mat np2Mat(np.ndarray ary):
if ary.ndim == 2:
return np2Mat2D(ary)
elif ary.ndim == 3:
return np2Mat3D(ary)
cdef object Mat2np(Mat m):
# Create buffer to transfer data from m.data
cdef Py_buffer buf_info
# Define the size / len of data
cdef size_t len = m.rows*m.cols*m.channels()*sizeof(CV_8UC3)
# Fill buffer
PyBuffer_FillInfo(&buf_info, NULL, m.data, len, 1, PyBUF_FULL_RO)
# Get Pyobject from buffer data
Pydata = PyMemoryView_FromBuffer(&buf_info)
# Create ndarray with data
shape_array = (m.rows, m.cols, m.channels())
ary = np.ndarray(shape=shape_array, buffer=Pydata, order='c', dtype=np.uint8)
# BGR -> RGB
ary = np.dstack((ary[...,2], ary[...,1], ary[...,0]))
# Convert to numpy array
pyarr = np.asarray(ary)
return pyarr
def np2Mat2np(nparray):
cdef Mat m
# Convert numpy array to cv::Mat
m = np2Mat(nparray)
# Convert cv::Mat to numpy array
pyarr = Mat2np(m)
return pyarr
cdef class PyMat:
cdef Mat mat
def __cinit__(self, np_mat):
self.mat = np2Mat(np_mat)
def get_mat(self):
return Mat2np(self.mat)
cpdef object PyPatchMatch_inpaint(np.ndarray input_img, np.ndarray mask_img, int radius):
cdef Mat input_mat
cdef Mat mask_mat
cdef Mat output_mat
input_mat = np2Mat(input_img)
mask_mat = np2Mat(mask_img)
output_mat = inpaintPatchMatch_mat(input_mat, mask_mat, radius)
output = Mat2np(output_mat)
return output