import numpy as np
import cv2
import os
dir = 'C:\\Project\\Interview Packet'
os.chdir(dir)
image = cv2.imread('us_flag_color.png')
template = cv2.imread('mask.png')
imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
templateGray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
template = cv2.Canny(template, 50, 200)
result = cv2.matchTemplate(imageGray, templateGray, cv2.TM_SQDIFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
w, h = template.shape[:2]
threshold = 0.8*max_val
loc = np.where( result >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.imwrite("res.png", image)
I've a US flag with stars on it and a mask image consisting a black star. Using the mask image I would like to detect all the stars in the US flag albeit colored differently. When I use the above code I could only get the stars labelled white recognized as illustrated by the below picture.
The box colored red has a star under it colored black matching that of the one in the mask image. I'm guessing this is because I'm using the gray image to identify these stars. As shown below the colored stars are faded in the process of graying that the algorithm is not able to distinguish them from the background color.
The original images are posted below: