Tuesday, December 8, 2015

OPENCV on Python on my WIndows 8.1 tablet

I have just installed OPENCV on Python on my WIndows 8.1 tablet and I have been playing with it like crazy. Opencv is a powerful tool to programmatically manipulate an image. It is like a low level version of Photoshop. And what happens when a programmer gets to programmaticaly manipulate an image? The possibilities are endless.

I had skipped the "hello world" part because I am not new to opencv and here is what I have tried to develop as part of my learning: finding the exact location of a small image taken from a larger image.

This ois the large image:

And obviously this is the small piece of image:


 And here is the result:

 
 
And here is the python code I used:
# import the necessary packages
import numpy as np
import cv2

# load the big_image  and small_image  images
big_image = cv2.imread('C:\\Users\\mybook\\Documents\\alpha.jpg')
small_image = cv2.imread('C:\\Users\\mybook\\Documents\\piece.jpg')
(small_imageHeight, small_imageWidth) = small_image.shape[:2]

# find the small_image in the big_image
result = cv2.matchTemplate(big_image, small_image, cv2.TM_CCOEFF)
(_, _, minLoc, maxLoc) = cv2.minMaxLoc(result)

# grab the bounding box of small_image  and extract it from
# the big image
topLeft = maxLoc
botRight = (topLeft[0] + small_imageWidth, topLeft[1] + small_imageHeight)
roi = big_image[topLeft[1]:botRight[1], topLeft[0]:botRight[0]]

# construct a darkened transparent 'layer' to darken everything
# in the big_image except for small_image
mask = np.zeros(big_image.shape, dtype = "uint8")
big_image = cv2.addWeighted(big_image, 0.25, mask, 0.75, 0)

# put the original small_image  back in the image so that it is
# 'brighter' than the rest of the image
big_image[topLeft[1]:botRight[1], topLeft[0]:botRight[0]] = roi

# display the images
cv2.imshow("Big_Image", big_image)
cv2.imshow("Small_Image", small_image)
cv2.waitKey(0)
This may a simple app but it can be useful for game development, or it even be further developed and improved to create an image search engine.

No comments:

Post a Comment