Overlay the template over the reference image using Python - python

So, I am stuck at a place where I need to superimpose a image in a homographed form to reduce the noise and allow us to reduce the load.
The image where I need to superimpose:
The image which I will be superimposing:
Now, the basketball court has to be superimposed over the 2d drawing, hence allowing me to track the court dynamically over video, thereby get a reference point to track the players inside the court.
Here is the code that I used as of now to track the area
import numpy as np
import cv2
from skimage.io import imread, imshow, imsave
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle
from skimage import transform
from skimage.color import rgb2gray
from skimage.feature import match_template
from skimage.feature import peak_local_max
import numpy as np
import glob
import os
from natsort import natsorted
def track_camera(image_path, num, path='./cam_trackings/'):
reference_image = imread("full-court.jpg")
# plt.figure(num=None, figsize=(8, 6), dpi=80)
# imshow(reference_image);
reference_image_gray = rgb2gray(reference_image)
# plt.figure(num=None, figsize=(8, 6), dpi=80)
# imshow(reference_image_gray);
template = rgb2gray(imread(image_path))
# imshow(template);
result = match_template(reference_image_gray, template)
# plt.figure(num=None, figsize=(8, 6), dpi=80)
# imshow(result, cmap='magma');
x, y = np.unravel_index(np.argmax(result), result.shape)
template_width, template_height = template.shape
rect = plt.Rectangle((y, x), template_height, template_width,
color='r', fc='none')
plt.figure(num=None, figsize=(8, 6), dpi=80)
plt.gca().add_patch(rect)
imshow(reference_image_gray);
# imsave(path+'cam_tracking'+str(num)+'.png', reference_image_gray)
plt.savefig(path+'cam_tracking'+str(num)+'.png')
plt.close()
And the output of this is as below (Tracked area):

Related

how to add data to cvlib

Does anyone knows how to add data to cvlib? I want to use
cv.detect_common_objects with my own data.
I was trying to do ant recogniton but cvlib doesn't have any ant data. I have to get answer fast.
code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
import cvlib as cv
from cvlib.object_detection import draw_bbox
from numpy.lib.polynomial import poly
#wcale nie z poradnika :D
img = cv2.imread("ant1.png")
img1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(10, 10))
plt.axis("off")
plt.imshow(img1)
plt.show()
box, label, count = cv.detect_common_objects(img)
output = draw_bbox(img, box, label, count)
output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(10, 10))
plt.axis("off")
plt.imshow(output)
plt.show()

How to fill area between curve and origin edge with colormap?

I have a data with coordinates X,Y similar to a Vertical Sine function, I want to fill the area between left edge and the curve generated using variable color with colormap on matplot, changes in color whith X value as the image (From Blue to Red). I've tried and get this result where start point and final point are conected by a line. I need to fill the left area.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
#Data
y=np.arange(0,10,0.01)
x=np.sin(y)*y+2
#Set Array
xx=np.asarray(x)
yy=np.asarray(y)
path = Path(np.array([xx,yy]).transpose())
patch = PathPatch(path, facecolor='none')
plt.gca().add_patch(patch)
im = plt.imshow(xx.reshape(yy.size,1), cmap=plt.cm.coolwarm,interpolation="nearest",
origin='left',extent=[-5,10,0,10],aspect="auto", clip_path=patch, clip_on=True)
im.set_clip_path(patch)
You could add two additional points lying on the y-axis to create the desired shape:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
y = np.linspace(0, 10, 200)
x = np.sin(y) * y + 2
path = Path(np.array([np.append(x, [-5, -5]), np.append(y, [y[-1], y[0]])]).T)
patch = PathPatch(path, facecolor='none')
plt.gca().add_patch(patch)
im = plt.imshow(x.reshape(y.size, 1), cmap=plt.cm.coolwarm, interpolation="nearest",
origin='lower', extent=[-5, 10, 0, 10], aspect="auto", clip_path=patch, clip_on=True)
plt.show()

Obtain box2d from superpixels segments

I am trying to use SLIC to obtain superpixels and get semantic segmentation of an image.
img = cv2.imread(img_name)
segments = slic(image, n_segments = numSegments, sigma = 3,convert2lab=True,max_iter=25)
How do I get the box2d for each of the segments? and if there a hierarchical tree of the segments how do I fetch that?
I did not read the original paper, but according to documentation it does not return a hierarchy.
I assume that you mean bounding boxes, so used the skimage example of Regionprops to get bounding boxes for each superpixel returned by SLIC.
Result:
Code:
from skimage.segmentation import slic
from skimage.data import astronaut
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from skimage.measure import label
from skimage.measure import regionprops
from skimage.color import label2rgb
img = astronaut()
segments = slic(img, n_segments=50, compactness = 100)
image_label_overlay = label2rgb(segments, image=img)
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(image_label_overlay)
for region in regionprops(segments):
minr, minc, maxr, maxc = region.bbox
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='red', linewidth=2)
ax.add_patch(rect)
plt.show()

matplotlib - savefig with text very slow

I just wondered about the performance of matplotlib.pyplot.savefig(). It's a simple map. With only the country-borders it takes around 1 sec.
When i print a grid of only 21x19 values with text() on the map it needs 3 sec! Why is that so? Is there a workatound?
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import pickle
import numpy as np
import time
plt.clf()
m = pickle.load(open('a.pickle','rb'))
c = pickle.load(open('b.pickle','rb'))
x, y = m(lons, lats) # compute map proj coordinates
for i in range(322,343,1): # lons
for j in range(97,116,1): # lats
plt.text(x[j,i], y[j,i], int(round(data[j,i])),fontsize=7, color='k', ha='center', va='center')
print time.clock()-t1
plt.savefig('/var/www/img/test.png', bbox_inches='tight',pad_inches=0.05, dpi=100)
print time.clock()-t1
plt.close('all')

Fill polygon by heat map

I need to fill my polygon using a heatmap. For source of polygon I've use shapefile.
This is my code:
import shapefile
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cm as mcm
import matplotlib.image as mpimg
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import pylab as plb
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_frame_on(False)
sf = shapefile.Reader("./data/boundary-polygon")
recs = sf.records()
shapes = sf.shapes()
print shapes[1].__dict__
Nshp = len(shapes)
cns = []
for nshp in xrange(Nshp):
cns.append(recs[nshp][1])
cns = np.array(cns)
cm = mcm.get_cmap('Dark2')
cccol = cm(1.*np.arange(Nshp)/Nshp)
# facecolor=cccol[nshp,:],
for nshp in xrange(Nshp):
ptchs = []
pts = np.array(shapes[nshp].points)
prt = shapes[nshp].parts
par = list(prt) + [pts.shape[0]]
for pij in xrange(len(prt)):
ptchs.append(Polygon(pts[par[pij]:par[pij+1]], alpha=1))
ax.add_collection(PatchCollection(ptchs,facecolors=((1, 1, 1, 1),),alpha=0.1 ,linewidths=1))
ax.set_xlim(54,67)
ax.set_ylim(50,57)
I want to change facecolors=((1, 1, 1, 1),) to facecolors=<image_of_my_heat_map>. Any help regarding this would be deeply appreciated.
Just set the polygons to be whatever color you want them to be:
ptchs=[]
for pij in xrange(len(prt)):
ptchs.append(Polygon(pts[par[pij]:par[pij+1]], alpha=1, color=your_color))
and then create the PatchCollection with the warg match_orginal:
ax.add_collection(PatchCollection(ptchs, match_orginal=True, alpha=0.1 ,linewidths=1))
Also see Why is matplotlib.PatchCollection messing with color of the patches?
I am not familiar with the shapefile API for reading the vector data/polygons. I typically use OGR to read GIS vector data. The colour per polygon can be stored as an attribute per feature or just as a scalar which is assigned a colour using the colourmap as you have done here.

Categories

Resources