Machine learning using python. Taking a look at how we use various libraries such as cv2, numpy and matplotlib. Beginner friendly code. Lots of comments and straight to the point.
2. What it is
• Applying machine learning in order for a machine to understand a certain image
and its characteristics
• In this example, we want the machine to learn characteristics of a certain bee
(template.jpg) and pick it from a picture of a number of bees.
• Template.jpg is the template we are using to train our model
• We are picking our bee from Bee1.jpg which has a number of bees in it:
3. Libraries used
• import cv2 #our computer library of choice which is open cv
• import numpy as np #library for mathemitical computation
• from matplotlib import pyplot as plt
• %matplotlib inline #to have our images shown within jupyter using the above line
4. Reading the image and the template
• image = cv2.imread('Bee1.jpg') #the image from which we are picking the bee
• img = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
• img_copy = img.copy() #making a numpy copy of our original image so we don’t
distort it when we are working on it
• template = cv2.imread('template_bee.jpg', 0) # this is the template showing us the
image of the bee we are looking for
• w, h= template.shape[::-1] #image dimensions and python starts counting from 0 and
so the -1
5. Matching our template with our image
• #Apply template matching using the function matchTemplate
• res = cv2.matchTemplate(img_copy,template,cv2.TM_CCOEFF_NORMED)
• min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
• #define the threshold; allowance for error
• threshold = 0.8
• loc = np.where(res >= threshold)
6. Identifying our bee
• #draw a bounding rectangle
• for pt in zip(*loc[::-1]): #for a certain point in our image
• cv2.rectangle(img_copy,pt,(pt[0]+w,pt[1]+h), (0,255,255),2) #draw our
rectangle
• plt.imshow(img_copy, cmap="gray") #this is plotting our image