def apply_median(k):
''' Apply the given kernel to images
This function searches through the images/source subfolder, and
uses your convolution funciton implemented in part0 to apply the given kernel
to each image found inside. It will then save the resulting images to the
images/filtered subfolder, appending their names with kernel_name.
'''
print 'applying median filter to images'
sourcefolder = os.path.abspath(os.path.join(os.curdir, 'images', 'source'))
outfolder = os.path.abspath(os.path.join(os.curdir, 'images', 'filtered'))
print 'Searching for images in {} folder'.format(sourcefolder)
exts = ['.bmp', '.pbm', '.pgm', '.ppm', '.sr', '.ras', '.jpeg', '.jpg',
'.jpe', '.jp2', '.tiff', '.tif', '.png']
for dirname, dirnames, filenames in os.walk(sourcefolder):
for filename in filenames:
name, ext = os.path.splitext(filename)
if ext in exts:
print "Reading image {}.".format(filename)
img = cv2.imread(os.path.join(dirname, filename))
print "Applying filter."
if len(img.shape) == 2:
outimg = part3.filter_median(img, k)
else:
outimg = []
for channel in range(img.shape[2]):
outimg.append(part3.filter_median(img[:,:,channel], k))
outimg = cv2.merge(outimg)
outpath = os.path.join(outfolder, name + 'median' + str(k) + ext)
print "Writing image {}.\n\n".format(outpath)
cv2.imwrite(outpath, outimg)
评论列表
文章目录