Smoothing create or replace function smooth(maxr integer, maxc integer, im_array integer[]) returns integer[] as $$ import numpy as np import scipy as sc import scipy.ndimage as ndi smooth = np.reshape(im_array, (maxr+1, maxc+1)) smooth = ndi.uniform_filter(smooth, size=3) return np.reshape(smooth.astype(int), (maxr+1)*(maxc+1)) $$ language plpythonu; select im_id, smooth(max(row), max(col), array_agg(blue_intensity order by row,col)) from (select im_id,row,col,blue_intensity from images_table where im_id=1878 order by im_id, row, col) t group by im_id distributed by (im_id);