How to go from STEP geometry to CSG - python

I am trying to transform a solid created in a CAD program (saved in a STEP file) into a CSG object constructed with simple primitives.
I am not very familiar with the different geometry file formats but as far as I understand it should be possible to do, at least with some simple solids, since the information about the face shapes etc. is stored in a STEP file. I have found this issue https://github.com/tpaviot/pythonocc-core/issues/470 which proves you can extract some of this information. However I am not sure this is enough to achieve my goal.
As an example, I would like to go from the following CAD design / STEP file:
to a CSG description which should describe the geometry as a big cylinder with three smaller cylinders as subtractions.
Ideally I would use a python library for this purpose, perhaps this library is a good candidate.
However I am afraid this isn't theoretically possible since I am not finding much information online.
As a last resort I could just mesh the solid and generate a CSG description using a tessellated solid, but I want to use simple primitives such as boxes or cylinders whenever possible.
I would love to know if this is possible to do and if so, I would love some resources to read about this. Thanks!

Related

Programmatically altering stl CAD files with Python

I have many stl CAD files for 3D printing and I was wondering how I can manipulate an individual CAD file by making a simple change programatically. Like if I want to double the dimensions of everything in the CAD file, how could I accomplish this in python? I could convert it to gcode if that makes things simpler.
I have come across FreeCad but I am not sure if this is the easiest and best way of programmatically altering CAD files. I also wanted an option that allows for freedom of manipulation beyond just size, maybe also seeing how I can programmatically alter the shape of the CAD file.
Well to be precise, STL files are even not meshes, but triangles soups. Which means that triangles are even not connected to each other (well they need to be adjacent to be used by software generatif g-code, but no obligation else)
just for clarification: g-code format is just a sequence of instructions for the machines (3d-printers, etc) so it's very good for printers, but also certainly the worst format to manipulate geometry.
one solution
you can use the python pymadcad module to deal with STL files
So for simple transformation operations (such as scale, translation etc)
from madcad import *
part = read('path/to/your_file.stl')
transformed = part.transform(mat3(2)) # scale by a factor 2 (diagonal matrix of 2)
write(transformed, 'path/to/output_file.stl')
If you need more complex operations (such as booleans, chamfers, etc) you will need to make the triangle connected again before the desired operations.
from madcad import *
part = read('path/to/your_file.stl')
part.mergeclose() # merge points at the same location
# your desired operations (example)
transformed = union(part, icosphere(vec3(1,1,1), 3.)) # add a sphere a diameter 3
write(transformed, 'path/to/output_file.stl')
note
pymadcad is internally using numpy-stl to import stl files, if you need only basic manipulations you can also only install that one
STL files are meshes. Their exterior is defined by triangulated surfaces. Meshes are notoriously difficult to modify after the fact. That's why you always want to save your designs in the native format and also in an open solid format like .STP or .IGES.
That said, simple scaling of a mesh is pretty easy and can be done trivially in FreeCAD.
You can do it in the gui in the mesh design workbench or through python. Here's a post about that:
https://forum.freecadweb.org/viewtopic.php?t=9109#p74047
FreeCAD also has some tools to convert a mesh into a solid. Results are usually less than spectacular but might be good enough depending on your needs. Search on the FreeCAD forum for posts about converting or look here: https://wiki.freecadweb.org/FreeCAD_and_Mesh_Import
Gcode doesn't say anything about the model itself. It specifies where a tool should move so it's just a series of directives that move a tool from place to place at a given speed. Going from Gcode to a model that you can edit is pretty difficult or impossible.

Easy monocular camera self-calibration algorithm

I have a video of a road/building and I want to create a 3D model out of it. The scene I am looking at is rigid and the drone is moving. I assume not having any extra info like camera pose, accelerations or GPS position. I would love to find a python implementation that I can adapt to my liking.
So far, I have decided to use the OpenCV calcOpticalFlowFarneback() for optical flow, which seems reasonably fast and accurate. With it, I can get the Fundamental Matrix F with findFundamentalMat(). So far so good.
Now, according to the tutorial I am following here, I am supposed to magically have the Calibration Matrix of the camera, which I obviously don't have nor plan to have available in the future app I am developing.
After some long research, I have found a paper (Self-calibration of a moving camera from point correspondences and
fundamental matrices) from 1997 that defines what I am looking for (with a nice summary here). I am looking for the simplest/easiest implementation possible, and I am stuck with these problems:
If the camera I am going to use changes exposure and focus automatically (no zoom), are the intrinsic parameters of the camera going to change?
I am not familiar with the Homotopy Continuation Method for solving equations numerically, plus they seem to be slow.
I intend to use the Extended Kalman Filter, but do not know where to start, knowing that a bad initialization leads to non-convergence.
Digging some more I found a Multi Camera Self Calibration toolbox open-source written for Octave with a Python wrapper. My last resort will be to break down the code and write it in Python directly. Any other options?
Note: I do not want to use the a chess board nor the planarity constraint.
Is there any other way to very accurately self-calibrate my camera? After 20 years of research since 1997, has anyone come up with a more straightforward method??
Is this a one-shot thing, or are you developing an app to process lots videos like these automatically?
If the former, I'd rather use an integrated tool like Blender. Look up one of the motion tracking (or "matchmoving") tutorials on youtube to get an idea of it, for example this one.

Python: create SVG

What I want is to create some electrical symbols (transistor, capacitor, diode...) and than to use them like a puzzle elements to create electrical scheme drawing and save it as one SVG file.
My idea is
Use some kind of scheme for SVG (like XML Scheme) to create complex electrical symbols out of basic shapes: lines, circles, square...
Use instances of those symbols, with coordinates (which I load in Python) to put them in the right place in final electrical scheme
Save it as .SVG
What is the best way to do that? (SVGFig looks like it would do it, but I can't find similar examples)
Examples would be appreciated.
Hm, not sure if it helps you, but there was a program, called Dia diagram editor, meant for drawing SVGs and equipped with Python command line. It's quite glitchy, though, but at least it has a good set of electrical symbols within and works with SVG. Good luck!
Here are some examples:
https://mail.gnome.org/archives/dia-list/2010-August/msg00014.html
https://live.gnome.org/Dia/Python

Python graph like windirstat?

I'm interested in using python to make diagrams representing the size of values based on the size of squares (and optionally their colour). Basically I'm looking for a way to make overviews of a bunch of values like the good old program windirstat does with hard-drive usage (it basically makes a big square representing your harddrive and then smaller squares making up the area inside of it representing different programs, the bigger the square the larger the file, colour indicates the type of file). I'm fairly familiar with matplotlib, and I don't think it's possible to do something like this with it. Is there any other python package that would help? Any suggestions for something more low level if it's not? I guess I could do it manually if I could find a way to draw the boxes programatically (I don't really care about the format, but the option to export SVG as well as PNG would be nice).
Ultimately, it would be nice to have it be interactive like windirstat is, where if you were to hover over a particular square you get more information on it, and if you clicked on it maybe you'd go in and see the makeup of that particular square. I'm only familiar with wxpython for GUI stuff, not sure if it could be used for something like this. For now I'd be happy with just outputting them though.
Thanks a lot!
Alex
Edit:
Thanks guys, both your answers helped a lot.
You're looking for Treemapping algorithms. Once implemented, you can transform the output (which should be rectangles) into plotting commands to anything that can draw layered rectangles.
Edit:
More links and information:
If you don't mind reading papers, the browser-based d3 library provides for 'squarified' treemaps (js implementation). They reference this paper by Bruls, Huizing, and van Wijk. (This is also citation 3 on the wikipedia article)
I'd search on the algorithms listed on the linked Wikipedia article. For instance, they also link to this article, which describes an algorithm for "mixed treemaps". The paper also includes some interesting portions at the end describing transformations into other-than-rectangular shapes.
Squarified certainly appears to be the most common variety around. The above links should give you enough to work towards a solution or, even, directly port the d3 implementation. However, the cost of grokking d3's model (which is something like a declarative form of jQuery) may be somewhat high. At first glance, though, the implementation appears relatively straightforward.
Squaremap does this. I haven't used it (I only know it from RunSnakeRun) and its documentation is severely lacking, but it seems to work.

How can I detect and track people using OpenCV?

I have a camera that will be stationary, pointed at an indoors area. People will walk past the camera, within about 5 meters of it. Using OpenCV, I want to detect individuals walking past - my ideal return is an array of detected individuals, with bounding rectangles.
I've looked at several of the built-in samples:
None of the Python samples really apply
The C blob tracking sample looks promising, but doesn't accept live video, which makes testing difficult. It's also the most complicated of the samples, making extracting the relevant knowledge and converting it to the Python API problematic.
The C 'motempl' sample also looks promising, in that it calculates a silhouette from subsequent video frames. Presumably I could then use that to find strongly connected components and extract individual blobs and their bounding boxes - but I'm still left trying to figure out a way to identify blobs found in subsequent frames as the same blob.
Is anyone able to provide guidance or samples for doing this - preferably in Python?
The latest SVN version of OpenCV contains an (undocumented) implementation of HOG-based pedestrian detection. It even comes with a pre-trained detector and a python wrapper. The basic usage is as follows:
from cv import *
storage = CreateMemStorage(0)
img = LoadImage(file) # or read from camera
found = list(HOGDetectMultiScale(img, storage, win_stride=(8,8),
padding=(32,32), scale=1.05, group_threshold=2))
So instead of tracking, you might just run the detector in each frame and use its output directly.
See src/cvaux/cvhog.cpp for the implementation and samples/python/peopledetect.py for a more complete python example (both in the OpenCV sources).
Nick,
What you are looking for is not people detection, but motion detection. If you tell us a lot more about what you are trying to solve/do, we can answer better.
Anyway, there are many ways to do motion detection depending on what you are going to do with the results. Simplest one would be differencing followed by thresholding while a complex one could be proper background modeling -> foreground subtraction -> morphological ops -> connected component analysis, followed by blob analysis if required. Download the opencv code and look in samples directory. You might see what you are looking for. Also, there is an Oreilly book on OCV.
Hope this helps,
Nand
This is clearly a non-trivial task. You'll have to look into scientific publications for inspiration (Google Scholar is your friend here). Here's a paper about human detection and tracking: Human tracking by fast mean shift mode seeking
This is similar to a project we did as part of a Computer Vision course, and I can tell you right now that it is a hard problem to get right.
You could use foreground/background segmentation, find all blobs and then decide that they are a person. The problem is that it will not work very well since people tend to go together, go past each other and so on, so a blob might very well consist of two persons and then you will see that blob splitting and merging as they walk along.
You will need some method of discriminating between multiple persons in one blob. This is not a problem I expect anyone being able to answer in a single SO-post.
My advice is to dive into the available research and see if you can find anything there. The problem is not unsolvavble considering that there exists products which do this: Autoliv has a product to detect pedestrians using an IR-camera on a car, and I have seen other products which deal with counting customers entering and exiting stores.

Categories