Last active
August 29, 2015 14:09
-
-
Save vatsan/07dc303636e904e18372 to your computer and use it in GitHub Desktop.
native_apps_blog_canny_plpython
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-------------------------------------------------------------------------------------------------------------- | |
-- Gautam Muralidhar, Srivatsan Ramanujam, Oct-2014 | |
-- PL/Python UDF, which calls the native Canny edge detection application | |
-- Input: the raw image byte stream encoded as a comma-separated string and stored in a column in a HAWQ table | |
-- Output: a composite type as defined in Figure 5. | |
-------------------------------------------------------------------------------------------------------------- | |
CREATE OR REPLACE FUNCTION canny_edge_detect(img varchar) | |
RETURNS canny_output_type | |
AS | |
$$ | |
import ctypes | |
from array import array | |
from numpy.ctypeslib import ndpointer | |
libfile = '/usr/local/lib/ds/canny_edge_detection.so' | |
# Load the shared object of the native Canny edge detection application | |
# GD is a global dictionary supplied by PL/Python that is available to each user session | |
if(not GD.has_key('canny_edge_detection')): | |
GD['canny_edge_detection'] = ctypes.cdll.LoadLibrary(libfile) | |
dl = GD['canny_edge_detection'] | |
# Prepare to call the native getImgSizeFromByteStream function to determine the image size | |
getImgSize = dl.getImgSizeFromByteStream | |
# Specify the input argument types of the native function using ctypes mapping | |
getImgSize.argtypes = [ctypes.c_char_p, ctypes.c_uint] | |
# Specify the result type of the native function as an ndpointer from numpy.ctypeslib | |
getImgSize.restype = ndpointer(dtype=ctypes.c_uint,shape=(2,)) | |
# Map the comma-separated string representing the image byte stream to a character array | |
buf = array('b', map(int, img.split(','))).tostring() | |
# Call the native getImgSizeFromByteStream function | |
imgSize = getImgSize(ctypes.c_char_p(buf),ctypes.c_uint(len(buf)) ) | |
# Repeat above steps to call the native edgeDetectionFromByteStream function | |
edgeDetect = dl.edgeDetectionFromByteStream | |
edgeDetect.argtypes = [ctypes.c_char_p,ctypes.c_uint] | |
edgeDetect.restype = ndpointer(dtype=ctypes.c_uint,shape=(imgSize[0]*imgSize[1],)) | |
result = edgeDetect(ctypes.c_char_p(buf),ctypes.c_uint(len(buf))) | |
# Return the composite type | |
return [imgSize[0], imgSize[1], result] | |
$$ LANGUAGE PLPYTHONU; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment