Generate heatmap image of lines - python

I have this graph, which contains a lot of lines defined by 2 points. Now I would like to generate a heatmap. The result should be something similar to http://docs.ggplot2.org/current/geom_raster.html, except the heat of each cell is defined as how many lines intersect it. The result should be a numpy array for PIL.
I considered two things so far, one would be to iterate over all lines and grids and calculate the distance from the two with this and if the distance is smaller than between two cells, it's in there. This is possible because in the actual data, the lines have a certain minimum length.
Another possibility to intersect each line with each grid cell and check if it's in there. But that sounds expensive, but more accurate. Along the lines that you check each horizontal/vertical line for intersection and check in which cell it is.
Data sample. It's an Array[Array[Int, Int]]. Every pair of sub-arrays designates a line.

This sounds like what you want:
How to test if a line segment intersects an axis-aligned rectange in 2D?
In particular the top answer: https://stackoverflow.com/a/293052/66349
In summary:
check if both points of the line are to one side of the box (left, right, above, below) - if so, there is no intersection
otherwise, check if all four corners of the box are on the same side of the line - if they are not, then you have an intersection
Generally speaking, it might be faster to iterate over the line segments and test only a subset of heat map boxes (perhaps boxes that fall into the larger box defined by the two points of the line); rather than iterating over the heat map boxes and checking every line for intersections.

Related

How to check if there is a line segment between two given points?

I made a model that predicts electrical symbols and junctions:
image of model inference.
Given the xywh coordinates of each junctions' bounding box in a form of a dataframe: image of the dataframe, how would I make an output that stores the location of all the wires in a .txt file in a form of: (xstart,ystart), (xend,yend).
I'm stuck at writing a way to check if there is a valid line (wire) between any two given junctions.
data = df.loc[df['name'] == 'junction']
# iterates through all of the junctions
for index, row in data.iterrows():
for index2, row2 in data.iterrows():
check_if_wire_is_valid()
My attempt was to erase all electrical symbols (make everything in bounding boxes white except for junctions) from the inference image and run cv.HoughLinesP to find wires. How can I write a function that checks if the cv.HoughLinesP output lies between two junctions?
Note that the minimum distance that lies between two junctions should be greater than 1px because if I have a parallel circuit like such: top left and bottom right junction would "detect" more than 1px of line between them and misinterpret that as a valid line.
EDIT: minAreaRect on contours . I've drawn this circuit with no elements for simplification and testing. This is the resulting minAreaRect found for the given contours. I can't seem to find a way to properly validate lines from this.
My initial solution was to compare any two junctions and if they are relatively close on the x-axis, then I would say that those two junctions form a vertical wire, and if other two junctions were close on the y-axis I would conclude they form a horizontal wire. junction distance to axis.
Now, this would create a problem if I had a diagonal line. I'm trying find a solution that is consistent and applicable to every circuit. I believe I'm onto something with HoughLinesP method or contours but that's as far as my knowledge can assist me.
The main goal is to create an LTSpice readable circuit for simulating purposes. Should I change my method of finding valid lines? If so, what is your take on the problem?
This should be doable using findContours(). A wire is always a (roughly) straigt line, right ?
Paint the classified boxes white, as you said
threshold() to get a binary image with the wires (and other symbols and letters) in white, everything else black.
run findContours() on that to extract objects.
Get the bounding boxes (minAreaRect) for all contours
discard all contours with a too wide side ratio, those are letter or symbols, keep only those slim enough to be a wire
Now you got all wires as objects, similiar to the junction list. Now, for how to merge those two... Some options that come to mind:
Grow the boxes by a certain amount, and check if they overlap.
Interpolate a line from the wire boxes and check if they cross any intersection box close by.
Or the other way around: draw a line between intersections and check how much of it goes through a certain wire box.
This is a pure math problem, and i don't know what you performance requirements are. So i'll leave it at that.

Find "anomalous" curves in a "generic-linear" shape

I am not a mathematician but I am pretty sure my problem could be solved with a bit (maybe a lot?) of good maths.
Let me explain the problem with a picture.
I have a network (GIS data) which is composed of many linear segments.
Rarely, a curve is present throughout these segments and I would need to find a reasonable method to detect them rather automatically.
Given that I have the coordinates of my segments and the curves (the green dots in the picture), would you reccomend a reasonable way to detect these curves?
I am not sure but it could be similar to the opposite of what is asked in this other SO question, but I don't actually have a function to calculate a second derivative, only line segments (and curves) made by vertices...
Assuming you can easily list out the points in a segment and iterate over them, and that a segment is "mostly" linear, you can take the end-points of a segment and interpolate a line between them.
Next, check if each point of the segment lies on the interpolated line and add a margin of error.
You can then assume that several adjacent points of the segment that do not lie on the interpolated line make up a curve.
You may need to implement other checks:
Are the end-points are part of a straight segment -- i.e. that the segment does not end in a curve
Does the segment bend and should the segment be treated as two segments?
Can two curves be adjacent to one another without a point between them that's on the line?
To get started with python, I'd write the function is_on_line and loop over all the points, calling it each time to see if the point is on the line.
Excuse the verbose pseudo code (makes lots of assumptions about data structures, can be done in one loop), but this should help you break the problem apart to get started:
points_on_line = []
for idx, point in enumerate(segment):
result = is_on_line(
endpoint_1_x=segment[0].x,
endpoint_1_y=segment[0].y,
endpoint_2_x=segment[-1].x,
endpoint_2_y=segment[-1].y,
coord_x=point.x,
coord_y=point.y,
error_margin=0.1,
)
points_on_line.append((point, result,))
for point, on_line in points_on_line:
# figure out where your curves are

How to find polygon vertices from edge detection images?

1. The problem
Given the images of a house roof, I am trying to find the contours of the roofs. I have labelled data available (as polygon vertices) which I interpolate and create the truth image which is shown below
I use canny, hough-lines, LBP features to train an ML model the results look decent. the model output is shown in the middle, and overlay on test image is shown on right.
2. What I need.
The final output should really be a set of polygons and I need to find the points on which these polygons should be drawn (see the highlighted points in image below). So the output can be set of n line segments. where each line segment is 2 points [(x1,y1),(x2,y2)]
3. What are my thoughts/ideas;
a. Erosion,Dilation,Opening,closing,skeletonize operations
While these operations make the lines in the above image much neater, they don’t help me find the polygon vertices I am looking for.
I'd like to fit (a number of) lines to the white pixels in the image (something like hough lines).
The intersections of these lines would give me the vertices for the polygons I am looking for.
I am wondering if there is a more standard/better way of accomplishing the above.
I think HoughLinesP will help you in your goal. It will find line segments and output them in a vector [x1,y1,x2,y2] where (x,y) pairs represent the start and endpoints of line segments.
Each vertex should be near the end of 2 or more line segments. You go through each of the endpoints and count how many times they appear. When you've processed all the points you can eliminate any that have less than 2 occurances. Of course you will need some small threshold for determining a point is unique because the gaps in the lines some psuedocode: dist(point1, point2) < some_delta_threshold
I'm not sure how you would find the polygons at this point, but hopefully this offers some assistance

Python QuadTree index returning nodes

I have a bounding box of a city containing points. I would like to divide this bounding box into sub boxes according to the importance of the points. For example, regions with more points should correspond to higher number of sub-boxes. Regions with less points should respond to less boxes with larger width.
I understood that a good data structure for that is a quad tree or maybe a KD-Tree. It turns out that most of these libraries just return me the nearest neighbor (This is their main use). I would like to have not the nearest neighbor but the sub box of a point. (lets say leaf id) Is this possible? or event the Quadtree-Data structure the correct to use ?
In other words I need the quad tree just to divide the region into sub boxes and not to be used as an index.
The naive solution is to just to divide the bounding box into equal sub boxes.
This is essentially what an R-Tree does. It produces a more or less balanced tree, based on bounding rectangles (boxes), but based on the number of geometric objects that fit inside the box, not on the boxes's area. KD-Trees, on the other hand, recursively divide a space first in the x and then in the y direction, which can make for very efficient searching, but can not be adjusted for areas with a lower or higher density of points. There is a Python implementation of R-Trees here, https://pypi.python.org/pypi/Rtree/. I have never used this (it is built into Postgres/Postgis which I use all the time), but I looks like it could be useful for what you describe.

Calculating and Plotting 2nd moment of image

I am trying to plot the 2nd moments onto a image file (the image file is a numpy array for brightness distribution). I have a rough understanding that 2nd moment is sort of like moment of inertia (Ixx,Iyy) which is a tensor but I am not too sure how to calculate it and how it would translate into two intersecting lines with the centroid at its intersection. I tried using scipy.stats.mstats.moment but I am unsure what to put as axis if I just want two 2nd moments that intersects at centroid.
Also it returns an array but I am not exactly sure what the values in the array signify, and how that relate to what I am going to plot (because the scatter method in the plotting module takes in at least 2 corresponding values in order to be plotted) ?
Thank you.

Categories

Resources