This piece of code shows how to sharpen a grayscale image (for color images do the same for each channel).
Sharpening is performed by applying a Laplacian operator on the image and adding the output to the original image.
Finally, this is the operator used (Laplacian+image):
-1 -1 -1
-1 9 -1
-1 -1 -1
-1 -1 -1
(see this nice application in which you can perform convolution with the above operator on a given image)
The code (assumes an image named imname is loadable, final output is stored in image named gray):
gray=cvLoadImage(imname,0)
imwidth = gray.rows
imheight = gray.cols
# convert to 32 bit
gray2=cvCreateImage (cvSize (imheight, imwidth), 32, 1)
for r in range(gray.rows):
for c in range(gray.cols):
gray2[r][c]=gray[r][c]
# define the filter:
lapl=cvCreateImage (cvSize (imheight, imwidth), 32, 1)
m=cvCreateImage (cvSize (3,3), 32, 1)
m[0][0]=-1
m[0][1]=-1
m[0][2]=-1
m[2][0]=-1
m[2][1]=-1
m[2][2]=-1
m[1][0]=-1
m[1][2]=-1
m[1][1]=8
cvFilter2D(gray2,lapl,m)
maxv=0
for r in range(gray.rows):
for c in range(gray.cols):
if(lapl[r][c]>maxv):
maxv=lapl[r][c]
for r in range(gray.rows):
for c in range(gray.cols):
v=int(255*lapl[r][c]/maxv)
gray[r][c]=gray[r][c]+v
maxv=0
for r in range(gray.rows):
for c in range(gray.cols):
if(gray[r][c]>maxv):
maxv=gray[r][c]
for r in range(gray.rows):
for c in range(gray.cols):
v=int(255*gray[r][c]/maxv)
gray[r][c]=v
No comments:
Post a Comment