def overlay_frame(image, template, match_features, show_templates=False): list_template = template.create() hits = locate_templates(image, list_template, match_features) l = len(list_template) if l < 12 and show_templates: f, axarr = plt.subplots(1, l) for i in range(l): axarr[i].imshow(list_template[i][1]) overlay = drawBoxesOnRGB(image, hits, boxThickness=5) plt.figure(figsize=(30, 30)) plt.imshow(overlay)
cv2.imshow('No red white region', image_nored) cv2.waitKey(1) #In[4]: APPLY TEMPLATE MATCHING WITHOUT RED REGION listTemplate_inwhite = [('A', BGR_featureimg_kngp), ('B', BGR_featureimg_kngp_2), ('G', BGR_featureimg_kngp_3), ('D', BGR_featureimg_kngp_4) ] #,('E', BGR_featureimg_kngp_5)] Hits = matchTemplates(listTemplate_inwhite, image_nored, score_threshold=0.55, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0) Overlay_inwhite = drawBoxesOnRGB(image_nored, Hits, showLabel=True) total_inwhite = len(Hits) listTemplate_blueinwhite = [('*A', BGR_featureimg_kngn), ('*B', BGR_featureimg_kngn_2), ('*C', BGR_featureimg_kngn_3)] Hits_blueinwhite = matchTemplates(listTemplate_blueinwhite, image_nored, score_threshold=0.75, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0) Overlay_blueinwhite = drawBoxesOnRGB(image_nored, Hits_blueinwhite, showLabel=True)
for i in range(0, len(br1.TemplateName)): df1 = df[df.TemplateName == f1[i]] score = round(max(df1.Score), 2) score1 = round((score - 0.35), 2) df2 = df1[(df1.Score == score) | (df1.Score >= score1)] df3 = df3.append(df2) df3["name"] = name1 #df3.to_csv(name1+".csv",index=False) #Overlay1 = drawBoxesOnRGB(im, finalHits,showLabel=True,labelScale=0.4,labelColor=(0, 255, 255), boxThickness=2) Overlay2 = drawBoxesOnRGB( imageNoise, df3, showLabel=True, labelScale=0.2, labelColor=(0, 255, 255), boxThickness=1) ###########draw the box on image #path=r'D:\video_template\plots'###############path to save image # plt.savefig(path+"\\"+name1+'.png') plt.figure(figsize=(20, 20)) plt.axis("off") plt.imshow(Overlay2) plt.savefig(path + "/" + name1 + '.png') plt.close() br = df3[['TemplateName', 'name']] s2 = br.pivot_table(index=['name'],
import matplotlib.pyplot as plt import numpy as np fileID = r"C:\Users\MattiaV\Desktop\università\Interships\DynamicsOfGranularShapes\ParticleTracking\Images\First frames\f1.png" image = io.imread(fileID) temp_draft = image[300:500,500:670] temp0 = temp_draft[41:113,48:123] image2 = io.imread(r"C:\Users\MattiaV\Desktop\università\Interships\DynamicsOfGranularShapes\ParticleTracking\Images\First frames\f2.png") listTemplate = [] # Initialise figure f, axarr = plt.subplots(1,4) for i in np.arange(0, 360, 90): #rotated1 = t.rotate(temp0, i, preserve_range=True) #rotated = np.rint(rotated1).astype(int) # transforms array of float into array of int rotated = np.rot90(temp0, k=int(i/90)) # NB: np.rotate not good here, turns into float! listTemplate.append( (str(i%120), rotated ) ) axarr[int(i/90)].imshow(rotated) # We could also do some flipping with np.fliplr, flipud Hits = matchTemplates(listTemplate, image2, N_object=50, score_threshold=0.55, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0.22).sort_index() Overlay = drawBoxesOnRGB(image, Hits, boxThickness=5) plt.figure(figsize = (30,30)) plt.axis("off") plt.imshow(Overlay)
SampleImg, method=cv2.TM_CCOEFF_NORMED, score_threshold=0.89, maxOverlap=0, ) print("Found {} hits".format(len(Hits.index))) Hits #Is it becuase the images are not floated? # In[6]: #Show Image with Template Lables get_ipython().run_line_magic('matplotlib', 'notebook') Overlay = drawBoxesOnRGB(ColorImg, Hits, showLabel=True) plt.imshow(Overlay) # In[7]: #Print Results to Excel Spread Sheet PrintBerg = pd.DataFrame(Hits) print(PrintBerg) try: PrintBerg.to_excel(r'C:/Users/Beth/Desktop/PrintBerg.xlsx', index=False, header=True) except: print("ERROR: Could Not Print")
cv2.imshow('Red Removed Region', image_nored) cv2.waitKey(1) # In[4]: APPLY TEMPLATE MATCHING WITHOUT RED REGION listTemplate_inwhite = [ ('A', BGR_featureimg_kngp), ('B', BGR_featureimg_kngp_2), ('G', BGR_featureimg_kngp_3), ('D', BGR_featureimg_kngp_4) ] #,('E', BGR_featureimg_kngp_5)] Hits = matchTemplates(listTemplate_inwhite, image_nored, score_threshold=0.55, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0) Overlay_inwhite = drawBoxesOnRGB(image_nored, Hits, showLabel=True) total_inwhite = len(Hits) listTemplate_blueinwhite = [('*A', BGR_featureimg_kngn), ('*B', BGR_featureimg_kngn_2), ('*C', BGR_featureimg_kngn_3)] Hits_blueinwhite = matchTemplates(listTemplate_blueinwhite, image_nored, score_threshold=0.75, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0) Overlay_blueinwhite = drawBoxesOnRGB(image_nored, Hits_blueinwhite, showLabel=True)
df3 = pd.DataFrame(columns=[ "index", "TemplateName", "BBox", "Score", "width", "hight" ]) for i in range(0, len(br1.TemplateName)): df1 = df[df.TemplateName == f1[i]] score = round(max(df1.Score), 2) score1 = round((score - 0.35), 2) df2 = df1[(df1.Score == score) | (df1.Score >= score1)] df3 = df3.append(df2) df3["name"] = name1 Overlay2 = drawBoxesOnRGB(imageNoise, df3, showLabel=True, labelScale=0.4, labelColor=(0, 255, 255), boxThickness=2) plt.figure(figsize=(20, 20)) plt.axis("off") plt.imshow(Overlay2) plt.savefig(path + name1 + '.png') plt.close() br = df3[['TemplateName', 'name']] s2 = br.pivot_table(index=['name'], columns=['TemplateName'], aggfunc=len).fillna(0).reset_index() br2 = br.groupby(["name", 'TemplateName']).size().reset_index(name="Time")
images = os.listdir(input_dir) print(images) for image in images: imagefile = input_dir + "/" + image host = cv2.imread(imagefile) img = cv2.cvtColor(host, cv2.COLOR_BGR2GRAY) h, w = img.shape plt.imshow(host) plt.show() thres = float(input("enter threshold:")) tar = cv2.imread( "/home/younesh/Desktop/projects/TemplateMatching/tar007.png") hits = TemplateMmatching(tar, host, thres) # thresh = 0.326 print(hits) Overlay = drawBoxesOnRGB(host, hits, showLabel=True) plt.imshow(Overlay) plt.show() conform = input("should we write the data to the file?(y/n)") if (conform == "y"): coordinatesToFile(hits, image, h, w) while (conform == "n"): thres = float(input("enter threshold:")) hits = TemplateMmatching(tar, host, thres) # thresh = 0.326 Overlay = drawBoxesOnRGB(host, hits, showLabel=True) plt.imshow(Overlay) plt.show() conform = input("should we write the data to the file?(y/n)") if (conform == "y"): coordinatesToFile(hits, image, h, w)
break listTemplate = [('marker', resized)] Hits = matchTemplates( listTemplate, new_copy, N_object=4, score_threshold=0.4, maxOverlap=0, method=cv2.TM_CCOEFF_NORMED) #,searchBox=(76,781,1856,353) Overlay = paper.copy() for index in Hits.index: x1, y1, w, h = Hits.BBox[index] Overlay = drawBoxesOnRGB(paper, Hits) Sum_scores = Sum_scores + Hits.Score[index] #print("Sum_scores : ",Sum_scores) #cv2.imshow('template_matched_paper',cv2.resize(Overlay,(620,620))) #cv2.waitKey(0) ### Checking is it the best scale ? if (allMaxT < Sum_scores): centres = [] allMaxT, best_scale = Sum_scores, scale Best_BBox = Hits.BBox.copy() h_resized = resized.shape[0] w_resized = resized.shape[1]
BBox, Score, templateName """ list_ = [] for i in os.listdir(template_dir): template = cv2.imread(template_dir + i, 0) list_.append((str(i), template)) match = matchTemplates(list_, image, score_threshold=thresh / 100, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0.30) print("Found {} Ellipses".format(len(match.index))) print(match) return match matches = match_image_template(image_gray, template_dir, 30) # %% image = cv2.imread("imgg2.png", ) draw_matches = drawBoxesOnRGB(image, matches, boxColor=(0, 255, 0), showLabel=False) plt.imshow(draw_matches)
cv2.waitKey(1) #In[4]: APPLY TEMPLATE MATCHING WITHOUT RED REGION listTemplate_inwhite = [('A', BGR_featureimg_kngp), ('B', BGR_featureimg_kngp_2), ('G', BGR_featureimg_kngp_3), ('D', BGR_featureimg_kngp_4) ] #,('E', BGR_featureimg_kngp_5)] Hits = matchTemplates(listTemplate_inwhite, image_nored, score_threshold=0.55, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0) Overlay_inwhite = drawBoxesOnRGB(BGR_cropimg_watershed_inred, Hits, showLabel=True) #Overlay_inwhite = drawBoxesOnRGB(image_nored, Hits, showLabel=True) total_inwhite = len(Hits) listTemplate_blueinwhite = [('*A', BGR_featureimg_kngn), ('*B', BGR_featureimg_kngn_2), ('*C', BGR_featureimg_kngn_3)] Hits_blueinwhite = matchTemplates(listTemplate_blueinwhite, image_nored, score_threshold=0.75, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0) Overlay_blueinwhite = drawBoxesOnRGB(BGR_cropimg_watershed_inred, Hits_blueinwhite,
imageNoise = cv2.add(image, noise, dtype=cv2.CV_8U) plt.figure(figsize=(10, 10)) plt.axis("off") plt.imshow(imageNoise, cmap="gray") # Call again matchTemplates with the noisy image this time, but the same template Hits_Noise = matchTemplates(listTemplate, imageNoise, N_object=4, score_threshold=0.3, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0.3) print("Initial detections") print(Hits) print("\nDetections with noise") print(Hits_Noise) Overlay1 = drawBoxesOnRGB(image, Hits, boxThickness=5) Overlay2 = drawBoxesOnRGB(imageNoise, Hits_Noise, boxThickness=5) plt.figure(figsize=(10, 10)) plt.axis("off") plt.imshow(Overlay1) plt.figure(figsize=(10, 10)) plt.axis("off") plt.imshow(Overlay2)
smallCoin = coins()[37:37 + 38, 80:80 + 41] plt.imshow(smallCoin, cmap="gray") # 1st format the template into a list of tuple (label, templateImage) listTemplate = [('small', smallCoin)] # Then call the function matchTemplates (here a single template) Hits = matchTemplates(listTemplate, image, score_threshold=0.5, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0) print("Found {} hits".format(len(Hits.index))) Overlay = drawBoxesOnRGB(image, Hits, showLabel=True) plt.imshow(Overlay) Hits = matchTemplates(listTemplate, image, score_threshold=0.4, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0) Overlay = drawBoxesOnRGB(image, Hits, showLabel=True) plt.imshow(Overlay) largeCoin = coins()[14:14 + 59, 302:302 + 65] plt.figure(0) plt.imshow(smallCoin, cmap="gray") plt.figure(1) plt.imshow(largeCoin, cmap="gray")