Tuesday, October 12, 2010

Laplacian filter using OpenCV and Python

import cv

# Load the image, replace filename with any JPG you like
img = cv.LoadImage("olympus.jpg")
# create buffer for grayscle
tmp = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 1)
#  convert color to grayscale
cv.CvtColor(img, tmp, cv.CV_BGR2GRAY)
# create destination buffer
dst = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_32F, 1)
# execute the filter: 3rd parameter is mask size, default = 3
cv.Laplace(tmp, dst)
# save image to disk
cv.SaveImage("saved.jpg", dst)

You can shorten the code by converting to grayscale on the fly like so:
import cv

img = cv.LoadImage("olympus.jpg", 2)
dst = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_32F, 1)
cv.Laplace(img, dst) # 3rd parameter is mask size, default = 3
cv.SaveImage("saved.jpg", dst)
Instead of saving to disk, you may want to display the result on a new window. Not shown here..

No comments:

Post a Comment