Convert point/dot annotation in to gaussian density map - python

I'm studying this paper: https://papers.nips.cc/paper/2010/file/fe73f687e5bc5280214e0486b273a5f9-Paper.pdf and I'm struggling at the function below:
Basically in an image, each person will be annotated a dot rather than bounding box or segmentation. The paper proposed a way to convert a dot into Gaussian density map, which acts as a ground truth. I have try numpy.random.multivariate_normal but it seems not working.

I am working on a research problem involving density maps. This code assumes you are looping over a list of text files, where each text file has the point annotations (or you are converting from object to point annotations, like I did). It also assumes that you have a list of annotations with (x,y) centre points to work with (after reading/processing said text file).
You can find a good implementation of this here:
https://github.com/CommissarMa/MCNN-pytorch/blob/master/data_preparation/k_nearest_gaussian_kernel.py
The above has some extra code for adaptive kernels.
The below code in context (with a lot more 'fluff') is here:
https://github.com/MattSkiff/cow_flow/blob/master/data_loader.py
Here is the code I used:
# running gaussian filter over points as in crowdcount mcnn
density_map = np.zeros((img_size[1],img_size[0]), dtype=np.float32)
# add points onto basemap
for point in annotations:
base_map = np.zeros((img_size[1], img_size[0]), dtype=np.float32)
# subtract 1 to account for 0 indexing
base_map[int(round(point[1]*img_size[1])-1),
int(round(point[0]*img_size[0])-1)] += 1
density_map += scipy.ndimage.filters.gaussian_filter(base_map, sigma = sigma, mode='constant')
This should create a density map that does what you want. Using 'imshow' on an ax object from matplotlib (e.g. ax.imshow(density,cmap='hot',interpolation='nearest') should produce a density map like so (I've added the aerial image to indicate what is being labelled):

Related

How to classify the points by a specific polylline

There is a boundary inside China, which divide the region as North-South. I have drawn this boundary as a polyline format shapefile Download link.
I want to divide those points in the following figures into "North" and "South". Is there any useful function in Python can achieve this.
fiona has point.within function to test points within/out a polygon, but I have not searched a suitable function to divide multiple points by polyline.
Any advices or tips would be appreciated!
updated
According to the valuable suggestion made by Prune, I worked it out. The codes are provided as follows:
from shapely.geometry import shape
from shapely.geometry import LineString
# loading the boundary layer
import fiona
fname = './N-S_boundary.shp'
line1 = fiona.open(fname)
line1 = shape(line1.next()['geometry'])
# set a end point which is the southernmost for all stations.
end_point = (dy[dy['lat']==dy['lat'].min()]['lon'].values[0],dy[dy['lat']==dy['lat'].min()]['lat'].values[0])
# loop all monitoring stations for classification
dy['NS']= np.nan
for i in range(0,len(dy),1):
start_point = (dy['lon'].iloc[i],dy['lat'].iloc[i])
line2 = LineString([start_point, end_point])
if line1.intersection(line2).is_empty:
dy["NS"].iloc[i]='S'
else:
dy["NS"].iloc[i]='N'
color_dict= {'N':'steelblue','S':'r'}
dy['site_color']=dy['NS'].map(color_dict)
You can apply a simple property from topology.
First, make sure that your boundary partitions the universe (all available points you're dealing with). You may need to extend the boundary through the ocean to finish this.
Now, pick any reference point that is labeled as to the region -- to define "North" and "South", you must have at least one such point. w.l.o.g. assume it's a "South" point called Z.
Now, for each point A you want to classify, draw a continuous path (a straight one is usually easiest, but not required) from A to Z. Find the intersections of this path with the boundary. If you have an even quantity of intersections, then A is in the same class ("South") as Z; other wise, it's in the other class ("North").
Note that this requires a topological property of "partition" -- there are no tangents to the boundary line: if your path touches the boundary, it must cross completely.

NurbsCurve MatrixMath Maya api Python

I am creating a toolset for creating nurbs curves/surfaces inside maya using python.
I have a set of dictionaries that include cvPositions, knots, form etc. each of which describe a preset 3d shape (cube, circle, pyramid etc).
I also have a 3d matrix stored in the nodes metadata that is used as an offset for the shape. This allows you to scale/move/rotate the shape without moving the transform.
The problem is in the way I am applying this matrix is very slow:
First I will create a new (edit)transform at the position of the (orig)transform containing the curves.
Next I will transfer cv positions in world space from (orig)transform to (edit)transform
Next i will move the (edit)transform into the matrix position.
Finally I will transfer the cvPositions back to the (orig)transform
When creating hundreds of shapes, this is becoming prohibitively slow...
Can someone describe a mathematical way to apply a matrix to a set of 3d points?
Perhaps using one of the math modules or numpy?
Alternatively,
Is there a way using OpenMaya api functions to do this? Perhaps with MPointArray? This is as far as I have gotten on that front:
crv = OpenMaya.MFnNurbsCurve( self.dagPath )
cvs = OpenMaya.MPointArray()
space = OpenMaya.MSpace.kWorld
crv.getCVs(cvs, space)
positions = []
for i in range(cvs.length()):
pt = cvs[i]
positions.append( (pt[0], pt[1], pt[2]) )
The easiest method is to use pymel's built-in versions of points and matrices (pymel is built in to maya 2011+). The math types are in pymel.datatatypes; here's an example of transforming a point by a matrix in pymel:
import pymel.core as pm
pt = pm.datatypes.Point(0,0,0)
mt = pm.datatypes.Matrix(1,0,0,0, 0,1,0,0, 0,0,1,0, 5,5,5,1 )
moved = pt * mt
print moved
# [5,5,5]
Pymel points and matrices will let you do your algorithm. The math is going to be done in the API but the Python <> C++ conversions may still make it feel pretty slow for big data.
It sounds like you're basically re-creating 'freeze transforms' followed by 'zero pivots'. Maybe you should try that as an alternative to doing this in python math...

Detect the size of a QR Code in Python using OpenCV and Zbar

I have code that takes an image from the webcam, scans it for QR codes using zBar and returns the value of the code and an image with the QR code highlighted (based off http://sourceforge.net/p/qrtracker/wiki/Home/). How can I also make it tell me the size of the code (as a pixel value or % of the screen)?
Additional question: is there a way to detect how skewed it is (e.g rotation in Z about the Y-axis)?
Regarding the size of Code
zBar provides a method to do this in terms of pixel values (Once you know the size in pixel values, you can find it in %)
I would like to extend the code here: http://sourceforge.net/apps/mediawiki/zbar/index.php?title=HOWTO:_Scan_images_using_the_API
Above code finds a QR code in an image, prints its data etc. Now checking last few lines of code:
import math
scanner.scan(image)
[a,b,c,d] = x.location # it returns the four corners of the QR code in an order
w = math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) # Just distance between two points
h = math.sqrt((b[0]-c[0])**2 + (b[1]-c[1])**2)
Area = w*h
Skewness of QRCode
I think you want to transform it into a pre-defined shape (like square, rectangle, etc). If so, you can define corners of a pre-defined shape, say ((100,100), (300,100),(300,300),(100,300)). Then find the perspective transform and apply the transformation if you would like. An example in OpenCV is provided here: http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html#perspective-transformation

How can I take a list of points that create a line and extend them into polygons inward of a certain length?

I have gps coordinates. They are just points that create an outline in a few different places, . I want to be able to have a script convert these points into polygons that extend X distance inwards, and also- a way for them to extend both inwards and outwards.
So if I had something like this:
(dots are points)
00000000000000000
00000000000000000
00............000
00.0000000000.000
00.0000000000.000
00.0000000000.000
00.0000000000.000
00.0000000000.000
00............000
00000000000000000
00000000000000000
I could run this program with a distance of 1 and "inwards", and I would end up with a polygon of # shape:
00000000000000000
00000000000000000
00&&&&&&&&&&&&000
00&&&&&&&&&&&&000
00&&00000000&&000
00&&00000000&&000
00&&00000000&&000
00&&&&&&&&&&&&000
00&&&&&&&&&&&&000
00000000000000000
00000000000000000
So far I have tried using circles and then reducing them but it seems wrong / not really feasible. This isn't being performed on a grid, actually it used floats for coordinates.
Any libraries that could do this as well are appreciated.
GDAL/OGR is another option. Ultimately what you want to do is a buffer. To expand your polygons shape outward use a buffer with a positive buffer distance, inwards it would be negative buffer distance. The following is a simple example using a shapefile. Not sure what format your data is in, but I would be surprised if GDAL/OGR can't read it.
import osgeo.ogr
# using ESRI Shape file in this example but there are a number
# of different files this lib supports: http://www.gdal.org/ogr/ogr_formats.html
driver = osgeo.ogr.GetDriverByName('ESRI Shapefile')
osgeo.ogr.UseExceptions()
# Create a data source using the driver...
dataSource = driver.Open("/home/user1/data.shp")
# Get the layer
lyr = dataSource.GetLayer()
# Select the feature in this case using an attribute query
lyr.SetAttributeFilter("column = 'value'")
# verify that you have a feature selected
print 'features in layer:', lyr.GetFeatureCount()
# get the firest feature from the layer
feature = lyr.GetNextFeature()
# get the geometry from the feature
geom = feature.GetGeometryRef()
# perform a 100 unit buffer, not sure what units the coordinates of the
# the data you have are in.
bufferGeom = geom.buffer(100)
# bufferGeom is a geometry object, which is described here:
# <http://cosmicproject.org/OGR/ogr_classes.html#Geometry>
The following is a fantastic resource for getting started with working with spatial data using GDAL/ORG: http://www.gis.usu.edu/~chrisg/python/2009/
Api docs: http://cosmicproject.org/OGR/ogr_classes.html
finally here is the link to the GDAL/OGR page. http://www.gdal.org/
https://pypi.python.org/pypi/Shapely
Shapely is a very good 2d computational geometry library; the way I understand it, it reduces your problem to a single line of code.

Adding legend to complex plot made with mpmath

I've been using the cplot command from the mpmath library to plot a complex function. It works pretty easily, all I have to do is write cplot(G_fit, [0.001, v_max], [-v_max, v_max], points = 100000) and I get a fairly smooth graph of my function G_fit over 0.001 < Re(z) < v_max and -v_max < Im(y) < v_max. There are two problems though:
How do I add a legend? It says in the documentation that the magnitude of the function is represented by brightness and the phase angle is the hue. That's fine, but what are the magnitudes and hues? All I want to do is add a bar beside the graph that goes from black to white and gives numerical values for the magnitudes at those brightnesses.
Is there any way to plot just the magnitudes (ie. just brightness?)
Thanks, and sorry if this is trivial, but I couldn't find anything about this in the documentation.
My own research finds that:
Doesn't look like it.
Redefine your function to return the absolute value of its argument.

Categories