1
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.

enter image description here

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.

enter image description here

The original images are posted below:

  • mask: enter image description here
  • us flag: enter image description here
Dan Mašek
  • 17,852
  • 6
  • 57
  • 85
bb5kb
  • 51
  • 1
  • 8

1 Answers1

1

Usually,I process image with color info in HSV color space. I analysis the different channel in RGB and HSV, and find the V channel is the best for this question.

The BGR:

enter image description here

The HSV:

enter image description here

Then do template matching, I get this:

enter image description here


I think maybe use findContours will also do the work.

Kinght 金
  • 17,681
  • 4
  • 60
  • 74
  • can you please let me know how to control the thickness of the bounding boxes.I tried the following code and I get very thick bounding boxes that overlap with the stars. Please let me know how to reproduce the thickness of the boxes in your output. for pt in zip(*loc[::-1]): cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1, 8) – bb5kb Dec 13 '17 at 04:36
  • If you check the `loc` found by thresholded `cv2.minMaxLoc` result, you will find there are more than one pts in every region. And I adjust the ratio to `0.9`, so the pts become less, and the boxes seem thinner(but till more than one box for every star), so you just cann't really control the boxes' thinkness of every star. As I said, `findContours` would work better, because it find only one contour every star. – Kinght 金 Dec 13 '17 at 05:29