Free software for 3D medical data visualization

There are many great free software that is available on the internet. In this post, I want to list some of them which I’ve used in my work. These open-source software are actively maintained by the community and they provide numerous features for rapid prototyping as well as for research and development.

MeshLab

It is the open source system for processing and editing 3D triangular meshes. This software provides a great tool for editing, cleaning, healing, inspecting, rendering, texturing and converting meshes. It also offers features for processing raw data produced by 3D digitization tools/devices.
The software can be downloaded for free using the following link:
MeshLab (http://www.meshlab.net/#download)

3DSlicer

It is an open source platform for medical image informatics, image processing, and 3D visualization. It includes a rich set of features for registration and interactive segmentation and volume rendering of medical images which can be used for research in image-guided therapy. It is available on multiple operating systems: Linux, MacOS, and Windows. The software architecture is extensible with powerful plug-in capabilities for adding algorithms and applications.
It can be downloaded for free using the following link:
3DSlicer (https://www.slicer.org/)

For building the full source code, use the following link:
Source (https://www.slicer.org/wiki/Documentation/Nightly/Developers/Build_Instructions)

The Medical Imaging Interaction Toolkit (MITK)

It is a free open-source software system for development of interactive medical image processing software. It combines the Insight Toolkit (ITK) and Visualization Toolkit (VTK) with an application framework. There are many good features in this application framework. But I really liked an interaction concept based on state machines that help to structure complex interaction mechanisms. Organization of all application data is easy in a central, hierarchical repository called DataStorage.

It can be downloaded using the following link:
MITK (http://mitk.org/wiki/MITK)

ITK-SNAP

It is a free open-source software application that allows to segment structures in 3D medical images. It provides semi-automatic segmentation using active contour methods as well as manual delineation and image navigation. Some of its core features are:

Linked cursor for seamless 3D navigation
Manual segmentation in three orthogonal planes at once
A modern graphical user interface based on Qt
Support for many different 3D image formats, including NIfTI and DICOM
Support for concurrent, linked viewing, and segmentation of multiple images
Support for color, multi-channel, and time-variant images
3D cut-plane tool for fast post-processing of segmentation results
Extensive tutorial and video documentation

The software and all source code can be downloaded using the following link:
ITK-SNAP (http://www.itksnap.org/pmwiki/pmwiki.php)

ParaView

It is an open-source, multi-platform data analysis and visualization application. It was developed to analyze extremely large datasets using distributed memory computing resources. It includes a plethora of features for building visualizations to analyze complex data using qualitative and quantitative techniques. Built using foundation library VTK, it is maintained by Kitware.

More information can be found in the following link:
KitWare (https://www.paraview.org/)

Cppcon 2018 Trip Report – Part 2 of 2

This is a Part 2 of Cppcon 2018 Trip Report. This covers all sessions from Day 2 and Day 3 that I attended. See Part 1 that covers Day 0 and Day 1.

Day 2: Sept 25, Tuesday

What Do We Mean We Say Nothing At All? – Kate Gregory

This talk focussed on the communication that the code we write carries because writing code is a form of communication. She focussed on how our code carries invaluable information that we leave for future who may be ourselves or our colleagues. Following new features of C++17 were discussed briefly:
Fallthrough
Maybe Unused
No Discard

This talk demonstrated that in many places nothingness carries a meaning and how this helps in increasing the information others can get from this approach. The video for this code can be found in the following YouTube link:

Patterns and Techniques Used in the Houdini 3D Graphics Application – Mark Elendt

This talk discussed some of the patterns and approaches that have been successfully used in Houdini. Houdini has been used in Visual Effects, television shows, the creation of AAA video games and even for Scientific Visualization. In particular, Mark discussed the following topics:

Historical Perspective
Proceduralism in Houdini
Graphics Pipeline
Industry Standards
Embracing Modern C++
Specialized classes
Reflections on 25 years of C++

I really liked the Graphics Pipeline that he demonstrated and there is a tremendous amount of research that goes into the optimization of the pipeline. Every stage of the pipeline has a unique problem. He showed some of the tricks that they used in Houdini architecture for smooth user experience. The original application was called PRISM that was written entirely in C. And when they created Houdini that is all C++ based, they created several transitional applications in C++ for a smooth transition. They have a very good experience of working in C++ even before STL or boost was born. So they had to write lots of custom classes from scratch which had a lot of benefits and downsides in terms of learning and flexibility. One of the interesting things to note in this talk is their conversion strategy. With the adoption of newer compiler toolchains and to support the legacy requirements, they used aliases to make interfaces compatible. This is a common pattern that every mature software industry faces at some point.
For example, before atomic was added to C++, they had their own version of UT_AtomicInt class. To cope with the absence of namespace, they used the convention like UT that stands for Utility Class. Now, with the introduction of std::atomic, they used aliases as follows:

template<typename T>
using UT_AtomicInt<T> = std::atomic<T>;

This makes the legacy code not to break, but under the hood, it will be using the standard C++ version.

Another aspect of the talk was focussed on Houdini Geometry where they created lots of specialized classes to work with geometry. One unique feature of Houdini’s Graphics Studio is the use of the node network where each node does some specific operations. For typical projects with 3D models, this network can be quite complex. Nodes are the building blocks of the scene.

For learning details about the Networks and parameters, refer to the following online documentation:
https://www.sidefx.com/docs/houdini/network/index.html

Other data structures for optimally storing 3D geometry data like Paged Arrays were discussed.

The video for this talk can be found in the following YouTube link:

Book Signing – Bjarne Stroustrup, Nicolai Josuttius

Renowned authors like Bjarne and Nicolai were present in the bookstore exhibit to sign books and there were long lines.

Operator Overloading: History, Principles and Practice – Ben Deane

This talk discussed on the past, current and likely future practices of using operator overloading best practices. Following are key takeaways from this talk:
Use Operator Overloading when:

you have a natural binary function that combines your types
your types obey mathematical principles (associativity, etc)
you want users to be able to manipulate expressions
you want to make complex construction easier
you want users to intuit properties of your types

Don’t use (only) operators when:
you can provide better perf with an n-ary function
they aren’t yet ready for primetime (operator<=>)

Don’t:
break contrariety of operator== and operator!=
break associativity
be afraid to overload just one operator, if it makes sense (operator/)
overload operator&& operator|| operator, even with P0145
pick weird operators if your type is mathematical

Do:
use conventions other than mathematical ones
consider distinguishing your types to leverage affine spaces
use operators for non-commutative operations to leverage fold expressions
use UDLs as a counterpart to operators to help with construction
provide the whole set of related operators if you provide one

A new three-way comparison operator (spaceship operator <=>) that will be in C++20 were also discussed that would provide the following types:
std::strong_equality
std::weak_equality
std::strong_ordering
std::weak_ordering
std::partial_ordering
A call to operator<=> returns a value of one of these types

A Semi Compile/Run-time Map With (Nearly) Zero Overhead Lookup – Fabian Renn-Giles

This talk presented a technique on how to overcome the overhead for value look-up in an associative map container given some key. Some of the key highlights of this talk are:

Use of associative map to calculate the storage of key’s associated value at compile-time, but loading/storing the value and adding key/value pairs at the run-time.

Techniques for using such map for a super efficient cache using constexpr if and constexpr lambda expression from C++17.

 

Why and How to Roll Your Own std::function Implementation – Tom Poole

This talk presented how std::function was created in the JUCE open source library and discussed the differences between their implementation with others. The std::function from the Standard C++ may not be suitable for all use cases. For example, while processing realtime data or for other performance critical tasks, the heap memory allocations from std::function may be a bottleneck. So the JUCE open source rolled out their own implementation of std::function in order to optimize for dealing with real-time audio data.

The JUCE open source is available in the following GitHub page.
https://github.com/WeAreROLI/JUCE

For more information on JUCE, click the following link:
https://juce.com/

Progress With C++ Modules – Nathan Sidwell

This talk went over the progress of C++ modules in terms of GNU C++ compiler and covered the following topics in general:

Background of the modules-TS (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4720.pdf)
Changes since the first TS was published.
Build integration possibilities.
Implementation details in GCC.
Future plans on releases.

This blog post gives a nice introduction and motivation for C++ Modules.
View at Medium.com

Following page gives a nice summary of C++ modules experimental features in GCC.
https://gcc.gnu.org/wiki/cxx-modules

Day 3: Sept 26, Wednesday

These Aren’t the COM Objects You’re Looking For – Victor Ciura

COM stands for Component Object Model which is a binary-interface standard for software components developed by Microsoft in 1993. A brief introduction to COM can be found in the following wiki link:
https://en.wikipedia.org/wiki/Component_Object_Model

This session explored how COM programming has been changed since the usage of modern C++ features. It demonstrated new COM programming idioms with an example of modern COM usage which is C++/WinRT (Standard C++ language projection for the new Windows Runtime API). It also explored some tricks and best practices for error handling and debugging while doing COM memory management, data marshalling and string handling.

The talk for this video can be found in the following YouTube link:

The creator of C++/WinRT – Kenny Kerr (https://kennykerr.ca/) was also attending this talk. I’ve taken his course on Pluralsight on COM. I particularly went to this talk because I myself was learning about COM and WinRT 2 years ago. Following GitHub link provides some rudimentary examples that I wrote while learning COM.
https://github.com/amirkogit/comdemo
https://github.com/amirkogit/WinRT

Simplicity: Not Just For Beginners – Kate Gregory

This talk from Kate discussed on a theme on how to write a simple and better code. The simple code has following salient features:
Expressive, Readable, Understandable, Unsurprising, Transparent, Self-explanatory, Reassuring and Pleasant.

We need to clearly understand what a simpler code means. There were questions that were discussed like: Is simpler better? Is it faster to write a simple code? Does it run faster? The bottom rule is: You have to know your tools – the language, the libraries and idioms. Some of the tips for writing simple and expressive code were highlighted as follows:
The Easiest Step – Try to write code simply from the beginning
Good naming conventions
Short functions
Avoid a really long list of parameters – use abstractions
Don’t nest deeply – return early
Const all the things
Keep up with the standard

I truly agree her saying: “Programming is a social activity in which communication is a vital skill. The code you leave behind speaks.”

What to Expect From a Next-Generation C++ Build System – Boris Kolpackov

C++ community definitely lacks a uniform build system where we can rely on one consistent build. But this scenario is changing with the introduction of C++ Modules (may be in C++20) that would simplify our build system. This talk explored some of the design choices for making a next-generation build system that would benefit all C++ community. It demonstrated key features the next-generation C++ build systems should have and based on key design choices made in an open source build2 build toolchain. For more information on build2, see the following link:
https://build2.org/

The build2 project seems to be very promising in build system landscape. If you have used Rust for a while, you already have figured out the build system engine like Cargo is desperately missing in C++. The build2 project would definitely fill this gap. Some of the key features of build2 are:
Next generation Cargo like integrated build toolchain for C++
Covers entire project lifecycle: creation, development, testing and delivery.
Uniform and consistent interface across all platforms and Compilers
Fast, multi-threaded build system with parallel building and testing
Dependency-free, as all you need, is a C++ compiler

I believe the support for C++ modules would be the selling point for any next-generation build toolchain.

A Little Order: Delving into the STL Sorting Algorithms – Frederic Tingaud

This was an interesting talk that explored benchmarking of some of the algorithms from STL. Frederic is the creator of quick-bench.com which is an online micro-benchmarking tool that is intended to quickly and simply compare the performance of two or more code snippets.
The talk demonstrated a use case for sorting 1,000,000 elements vector to get the median using Clang 3.8 and GNU’s libstdcxx. The talk is heavily result driven and he described and compared the results that he got from different compiler vendors. The YouTube video of this talk can be found in the following link:

Value Semantics: Fast, Safe and Correct by Default – Nicole Mazzuca

This talk covered the meaning of value semantics and how the principles of value semantics and regularity can be utilized to make our code faster and more correct. She demonstrated the existing value semantic standard library types and also the user-defined types that follow this principle. Also, some useful optimization tricks to create faster code while keeping the benefits of value semantics were discussed.

105 STL Algorithms in Less Than an Hour – Jonathan Boccara

Jonathan’s blog FluentCpp is one of the best C++ blogs that I have found. I found this talk very interesting and useful. C++ standard has 105 algorithms including both C++11 and C++17. And, the list and variation of these algorithms are growing. So learning all those would take a tremendous amount of time and effort. But there is an approachable way to get familiar with these algorithms and use as much as possible in our everyday programming. The presentation highlighted different groups of algorithms, the patterns they form in STL and the relationship between these algorithms. This method makes the learning of a huge pool of algorithms more simpler and enjoyable as well.

The YouTube video of this presentation can be found below:

Cppcon 2018 Trip Report – Part 1 of 2

I attended Cppcon 2018 last month which was held from Sept 23- 29 in Bellevue, Washington, USA. This year I attended the full five days that was filled with lots of great content and a huge number of attendees as compared to the previous year. So I decided to give a trip report in multiple posts rather than a single long post.

This post summarizes all sessions that I attended on Day 0 and Day 1. As many sessions were running in parallel, it was not possible to attend all of them. But the good thing is: Cppcon videos become available on YouTube generally within 3-4 weeks after the conference is over. So you have sufficient videos to watch later after the conference all year round.

The conference consisted of the following:
1. Pre-conference class (Sept 22 and Sept 23)
2. Main conference (Sept 24- Sept 28) that consists of Keynotes, Plenary, Poster sessions, Lightning talks, Lightning Challenge and other activities.
3. Post-conference class (Sept 29 and Sept 30)

All Pre-conference and Post-conference classes have to be registered separately from the main conference and these classes are conducted by well-known authors and speakers from the C++ Community.

Day 0: Sept 23, Sunday

I arrived Bellevue in the evening. Fortunately, the weather was sunny and no sign of rain that is typical to this place. As soon as you reach the conference venue which was the Meydenbauer Center, you could already feel the conference has already started. There was a registration reception held in the late evening followed by poster sessions. There were quite a number of posters presented as compared to the last year. They mentioned that the number of posters grew almost doubled. Following are the posters that were presented:

  • A C++ tasking framework with compile-time dispatching and type-driven priority scheduling for HPC by David Haensel
  • CodeChecker: A static analysis infrastructure built on the LLVM/Clang Static Analyzer toolchain by György Orbán, Tibor Brunner, Gábor Horváth, Réka Kovács
  • CodeCompass: An Open Software Comprehension Framework by Zoltán Porkoláb, Tibor Brunner, Márton Csordás, Máté Cserép, Anett Fekete, Endre Fülöp, Gábor Horváth
  • Cpp-Taskflow: Fast Parallel Programming with Task Dependency Graphs by Tsung-Wei Huang, Chun-Xun Lin, Guannan Guo, Martin D. F. Wong
  • CTwik: Hot Reloading & Quick-Build System by Mohit Saini
  • Efficiently and Comprehensively Reproducing C++ Bug Reports with Sciunit by Zhihao Yuan, Tanu Malik
  • Feedback on practical use of c++17 std::filesystem::recursive_directory_iterator by Noel Tchidjo Moyo
  • Fighting Non-determinism in C++ Compilers by Mandeep Singh Grang
  • Fizz, a C++14 implementation of TLS 1.3 by Subodh Iyengar, Kyle Nekritz
  • Funky Pools – Active Containers for Refactoring Legacy Code by Norman Birkett
  • Hardware Memory Tagging makes C++ Memory-Safer by Kostya Serebryany
  • Lifting machine code instructions to LLVM bitcode by Peter Goodman
  • Modernizing HPC Software with C++11 by Ivo Kabadshow, Andreas Beckmann, David Haensel
  • The C++ Lands, its amazing creatures and weird beasts by Elena Sagalaeva, Vladimir Gorshunin
  • Using C++ to improve productivity in the platform with C API by Alexius Alvin, Gilang Hamidy

The links to these posters can be found here:
https://github.com/CppCon/CppCon2018

Unlike other sessions, the poster session remains for a week and attendees can view and ask questions to the presenters all week long. There was also a voting system where you get a chance to vote for two of your best posters. The final announcement for the winner for the best 3 posters was announced on the final day of the conference.

Day 1: Sept 24, Monday

The conference officially kicked-off at 9 AM with the Keynote from the creator of C++ – Bjarne Stroustrup. The following section gives a summary of all the sessions that I attended this day.

Keynote – Concepts: The Future of Generic Programming – Bjarne Stroustrup

This Keynote was a brief tour of concepts and how they would change the way we think about programming. He explained their role in the design and their benefits. Some of the take-ways from this talk are:
Concepts help us develop better designs that facilitate to improve interoperability and focus on fundamental issues and semantics.
Concepts provide a better specification of interfaces
Concepts simplify code
Concepts give precise and early error messages and few errors.

The video of this talk can be found in this YouTube link.

The C++ Execution Model – Bryce Adelstein Lelbach

This was a nice and valuable talk from Bryce Lelbach from NVIDIA. Following topics were covered in this talk:
What are threads in C++ and how do they interact?
What is Memory in C++?
Demonstration of how the code is executed in a typical C++ program.
How are C++ expressions and statements executed?
What are the semantics of calling a function in C++?

Overall, this talk covered a deeper understanding of how C++ code is executed and how concurrency works in C++ in a multi-threaded abstract machine of the C++ programming language.

Book Signing: Herb Sutter, Scott Meyers

There was a booth where you could purchase popular C++ and Computer Science books. Moreover, there was also a book signing event where C++ pioneers like Herb and Scott were signing their books. Undoubtedly there was a long line of attendees!

How to write Well-Behaved Value Wrappers – Simon Brand

I’ve been following Simon Brand’s blog posts (https://blog.tartanllama.xyz/) frequently, and it was pleasant to attend his talk in person. This talked explained the key considerations while designing many generic types that wrap a number of values into one object like std::optional or std::tuple. It covered the topics like implicit/explicit constructors, conditional deletion of special member functions, propagation of special member triviality, noexcept correctness, private inheritance, and comparison operators.

The Nightmare of Initialization in C++ – Nicolai Josuttis

This talk was probably the best session that I attended on Day 1. The talk was full of rant and frustration from Nicolai Josuttis. He is one of the expert in C++ and a distinguished author of the popular C++ titles. This talk explained how the new uniform Initialization that was introduced with C++11 became a disaster and how this got fixed along with C++14 and C++17. With different ways in C++ to initialize an object each having different rules, effects and usage depending on the context and goals, it surely creates a source of trouble for a day to day programming.

Nicolai is also writing a new book on C++17 that presents all new language and library features. Following is the link to his websites:
http://www.cppstd17.com/
http://www.josuttis.com/

Unwinding the Stack: Exploring How C++ Exceptions Work on Windows – James McNellis

This talk is also one of my favourites where James describes all about exceptions in the Windows environment. It explains in a step by step manner what happens under the hood when the exception is thrown in a program. In particular, this talk explores how C++ exceptions actually work in the Visual C++ implementation. One of the benefits of this talk is you can get a very useful information when debugging some tricky problems especially during postmortem debugging when you’re trying to figure out what went wrong before a program crashed. Although this session focussed on Windows environment, I think the concepts and tricks presented are fundamentally the same and can be applied in other platforms like Linux as well.

The slides for this talk can be found on this GitHub page.

In the next post, I will cover sessions for Day 2 and Day 3.

Creating C++17 enabled Qt projects

While using qmake as a build process for Qt projects, we can define several project configuration and compiler options using CONFIG . To enable C++11 or C++14, we can use:

CONFIG += C++11 or
CONFIG += C++14

However, C++17 is not yet recognized for Qt 5.11. So, instead we can use the following:

QMAKE_CXXFLAGS += /std:c++17

This post demonstrates a simple Qt Console application that has all of these compiler configurations so that it is easy to test C++17 features quickly using Qt project file (.pro) in QtCreator IDE.

To begin with, we need to have Qt 5.11 already installed. Next, we need to have the latest compiler which supports C++17. For this post, I have used Microsoft Visual C++ compiler (Microsoft Visual Studio 17 Community Edition).

In Qt Creator, add Kit with the following configurations:
Name: win64-vc15-qt11
Compiler: Microsoft Visual C++ Compiler (x86_amd64)
Qt Version: Qt 5.11.0 (msvc2017_64)

This is illustrated in the figure below:

cpp17_win64_qt11_kit

Once the right Kit is configured, we can create a simple Qt Console application named “Cpp17Test”. This will create the following files:
Cpp17Test.pro
main.cpp

The file Cpp17Test.pro looks as shown below:

QT -= gui

CONFIG += c++14 console
CONFIG -= app_bundle

QMAKE_CXXFLAGS += /std:c++17

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += main.cpp

In main.cpp file, we can include several headers that are supported in C++17. Also, we can test C++17 features. For this post, I have used examples from cppreference 

The main.cpp, where I’ve combined all examples, looks as shown below:

namespace StructuredBindings {
int run()
{
    std::cout << "Structured Bindings Demo\n";

    std::set myset;
    if (auto [iter, success] = myset.insert("Hello"); success)
        std::cout << "insert is successful. The value is " << std::quoted(*iter) << '\n';
    else
        std::cout << "The value " << std::quoted(*iter) << " already exists in the set\n";

    std::cout << "\n";
    return 0;
}
}
namespace Optional {
// optional can be used as the return type of a factory that may fail
std::optional create(bool b) {
    if (b)
        return "Godzilla";
    return {};
}

// std::nullopt can be used to create any (empty) std::optional
auto create2(bool b) {
    return b ? std::optional{"Godzilla"} : std::nullopt;
}

// std::reference_wrapper may be used to return a reference
auto create_ref(bool b) {
    static std::string value = "Godzilla";
    return b ? std::optional<std::reference_wrapper>{value}
             : std::nullopt;
}

int run()
{
    std::cout << "Optional Demo\n";

    std::cout << "create(false) returned "
              << create(false).value_or("empty") << '\n';

    // optional-returning factory functions are usable as conditions of while and if
    if (auto str = create2(true)) {
        std::cout << "create2(true) returned " << *str << '\n';
    }

    if (auto str = create_ref(true)) {
        // using get() to access the reference_wrapper's value
        std::cout << "create_ref(true) returned " <get() <get() = "Mothra";
        std::cout << "modifying it changed it to " <get() << '\n';
    }

    std::cout << "\n";
    return 0;
}
} // end namespace
namespace RandomNumbers {

//Select five numbers from 1 to 69 for the white balls; then select one number from 1 to 26 for the red Powerball.

int run()
{
    std::cout << "Random numbers demo\n";

    std::random_device rd {};
    auto mtgen = std::mt19937 {rd()};
    auto ud = std::uniform_int_distribution{1,69};

    // select five numbers for white balls
    std::cout << "Five numbers for white ball: ";

    for(auto i = 0; i < 5; ++i) {
        auto number = ud(mtgen);
        std::cout << number << " ";
    }

    std::cout << "\n";

    std::cout << "Powerball number: " << ud(mtgen) << "\n";

    return 0;
}

} // end namespace
namespace StringView {
int run()
{
    std::cout << "StringView Demo\n";

    std::string_view str_view("abcd");

    auto begin = str_view.begin();
    auto cbegin = str_view.cbegin();

    std::cout << *begin << '\n';
    std::cout << *cbegin << '\n';

    std::cout << std::boolalpha << (begin == cbegin) << '\n';
    std::cout << std::boolalpha << (*begin == *cbegin) << '\n';

    std::cout << "\n";
    return 0;
}
} // end namespace
namespace Variant {
using namespace std::literals;

int run()
{
    std::cout << "Variant Demo\n";

    std::variant v, w;
    v = 12; // v contains int
    int i = std::get(v);
    w = std::get(v);
    w = std::get(v); // same effect as the previous line
    w = v; // same effect as the previous line

//  std::get(v); // error: no double in [int, float]
//  std::get(v);      // error: valid index values are 0 and 1

    try {
      std::get(w); // w contains int, not float: will throw
    }
    catch (const std::bad_variant_access&) {}

    std::variant x("abc"); // converting constructors work when unambiguous
    x = "def"; // converting assignment also works when unambiguous

    std::variant y("abc"); // casts to bool when passed a char const *
    assert(std::holds_alternative(y)); // succeeds
    y = "xyz"s;
    assert(std::holds_alternative(y)); //succeeds

    std::cout << "\n";
    return 0;
}
} // end namespace
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    qDebug() << "C++17 Features Test\n";
 
    StructuredBindings::run();
    Optional::run();
    Any::run();
    Variant::run();
    MonoState::run();
    FileSystems::run();
    StringView::run();
 
    qDebug() << "End of C++17 Features Test\n";
 
    return a.exec();
}

We can add several small examples in main.cpp file to quickly test whether new C++17 features are supported by the compiler that is configured.

The source code can be found on my GitHub.

Weekly tech report (08/06-08/12)

1. Magic Leap One: The Time Has Come

A long-awaited official announcement from Magic Leap is finally here. Magic Leap One Creator Edition is now available for developers to play with. After many years of hard work, they have finally brought a unique spatial computing platform that is going to change our lifestyles. There are tons of stuff to learn about Magic Leap. As a developer, I am more interested to learn about the underlying technologies that make the Mixed Reality no longer a science fiction thing.

Following are some of the great resources to get started with Magic Leap’s Mixed Reality technologies:
https://creator.magicleap.com/learn/guides/design-creating-for-magic-leap
https://creator.magicleap.com/learn/reference
https://creator.magicleap.com/learn/tutorials

2. Boost version_1_68_0 Released

3. A weekly overview of most popular C++ news, articles and libraries

There are lots of things going on now in C++ community. And it’s easy to get overwhelmed with the influx of information that is too much to be absorbed. Awesome C++ newsletter provides a nice summary for links to various articles, news and libraries.

4. C++ antipatterns

Documents some common mistakes that developers make.

5. Fluent {C++}

New blog series on default parameters in C++.

6. Magic Leap One: Vive forAR

A very nice and comprehensive review of Magic Leap One Creator. The author discusses various AR and VR differences and how application are treated in these fields. This review really motivated me to learn more about Magic leap’s underlying technologies on Operating Systems, API, services and the app development platform.

7. Dictionaries in Python

This tutorial covers all about the dictionary data structure in python. It covers the following:
Defining a Dictionary
Accessing Dictionary values
Dictionary Keys vs List indices
Building a Dictionary incrementally
Restrictions on Dictionary Keys
Restrictions on Dictionary Values
Operators and Built-in Functions
Built-in Dictionary Methods

Weekly tech report (07/30-08/05)

1. Socket Programming in Python (Guide)

Very comprehensive tutorial on network socket Programming in Python. I thoroughly enjoyed reading this well-written article with lots of valuable tips and tricks while writing client and server applications. Although the article is quite long, it is worth reading. Moreover, it would be best to try hands on to see the applications that are being developed in action. The concepts described in this article could also be used as a starting point for developing your own network-based applications in Python.

2. Pluralsight course – Digital Realities – The Big Picture

This is a nice short introductory course for beginners who are new to digital realities like Virtual Reality(VR), Augmented Reality(AR) and Mixed Reality(MR). This course gives a big picture overview on these trending technologies and the tools and development environments that we can use to develop apps for VR, AR and MR. The author also discusses the impact it will have on different fields like education, healthcare, manufacturing and entertainment.

3. Modern C++ Secure Coding Practices: Const Correctness

This is a short course that discusses on const correctness techniques that can be utilized to develop secure C++ applications. The author demonstrates small demo applications where a bug in C++ program could lead to severe attacks from the hackers. These errors and loopholes from the programmer’s side can be controlled by using const correctness most of the time.

4. TensorFlow: Getting Started

As I am new to Deep Learning, I wanted to get a taste of it on how to build applications utilizing Deep Learning techniques. As TensorFlow is one of the popular framework used for building Neural Network applications, this course is a perfect starting point, to begin with. This course gives a very good overview of TensorFlow and how this can be used easily without much effort to build sophisticated applications with powerful deep neural networks. The course also briefly touches on Keras framework using TensorFlow as a backend and how this makes it even easier to build deep learning based applications.

5. MEDICAL IMAGES: THE ONLY PHOTOS NOT IN THE CLOUD

This short article describes how the modern cloud-based image storage can leverage machine learning and AI to tackle some of the difficult problems in the healthcare. Unlike the traditional storage mechanisms like CD and PACS (Picture Archiving and Communication Systems) where the clinical images are stored deep inside without convenient interoperability with the external systems, the cloud-based storage and access can open doors to developing various machine learning solutions using these data.

Weekly tech report (07/23-07/29)

1. Introducing the Python Language Server

This is a recent blog post from Microsoft regarding the updates to Visual Studio Code on Language Server Protocol (LSP) for Python. LSP defines the Protocol used between an editor or IDE and a language server that provides language features like autocomplete, go to definition, find all references etc. More details on LSP can be read at this site.
https://microsoft.github.io/language-server-protocol/

2. Python Weekly

Python Weekly is a Weekly newsletter that you can subscribe for free. It is a great resource to keep up-to-date on what’s happening in the Python community. The newsletter comes with a short and clear summary of various Python tools, frameworks and libraries that are released or updated recently. Moreover, it covers interesting articles and tutorials on data science, machine learning, computer vision and deep learning that uses various Python libraries.

3. Simple object tracking with OpenCV

I came to know about this blog just recently. This has been one of the most popular blog covering various topics on computer vision and deep learning. I hope to read more articles that are published in this blog and seems like it contains a lot of them!

4. Computer vision powered by machine learning will change the way we see the world

This article discusses the potential applications of computer vision in exciting fields like automobile, virtual reality, augmented reality and IoT.

5. Python – Tron Demo

A short demo application created by KDAB demonstrating the usage of Qt Quick and Qt 3D QML API using PySide2.

Using PySide2 and pydicom to display DICOM header information

This is a short tutorial that demonstrates how to use Python and Qt. In particular, we will use pydicom and PySide2 to browse DICOM files and display its header information.

pydicom is a pure Python package that is useful for working with DICOM files such as medical images, reports and radiotherapy objects. pydicom can be easily installed as follows:

pip install -U pydicom

To check if pydicom is installed properly, we can run the following code:

import os
import pydicom
from pydicom.data import get_testdata_files
filename = get_testdata_files("rtplan.dcm")[0]
ds = pydicom.dcmread(filename)
print(ds)

This is a code snippet taken from pydicom documentation which loads the test data files that comes with pydicom, loads the file and prints its dataset information.

For detail installation instructions and Getting Started guide, refer to pydicom website.

PySide2 is a recent release from Qt framework that allows Python developers to use the same Qt framework that C++ developers have been using. This is all made possible by Python bindings with a generator called Shiboken. Refer to my previous blog post on Python programming with Qt and Introduction to Qt Python bindings for details about this new release.

The final screenshot of our application looks like the following:

explore_dicom_files_pyside2_pydicom

Figure 1. Main Window

The “Browse” button allows setting the directory where DICOM files are located. All DICOM files have to be in .dcm extension. Once the DICOM files are found, they are displayed in a tabular format that has a table header ‘filename’ and ‘size’.

The filename can be selected in a table and when the user double clicks on the row, a new dialog box is displayed with all the DICOM header information as shown in the figure below:

explore_dicom_files_pyside2_pydicom_load_file

Figure 2. A dialog box displaying DICOM header information

The implementation is straightforward. First, we define a Window class that is derived from QtWidgets.QDialog. All UI elements are constructed in its constructor. Some helper functions for “Browse” button action events and finding DICOM files and populating it in a table are written.

The full source code for this example is given below:

import pydicom
from PySide2 import QtCore, QtWidgets

class Window(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.browseButton = self.createButton("&Browse...", self.browse)
        self.directoryComboBox = self.createComboBox(QtCore.QDir.currentPath())

        directoryLabel = QtWidgets.QLabel("In directory:")
        self.filesFoundLabel = QtWidgets.QLabel()

        self.createFilesTable()

        buttonsLayout = QtWidgets.QHBoxLayout()
        buttonsLayout.addStretch()

        mainLayout = QtWidgets.QGridLayout()
        mainLayout.addWidget(directoryLabel, 2, 0)
        mainLayout.addWidget(self.directoryComboBox, 2, 1)
        mainLayout.addWidget(self.browseButton, 2, 2)
        mainLayout.addWidget(self.filesTable, 3, 0, 1, 3)
        mainLayout.addWidget(self.filesFoundLabel, 4, 0)
        mainLayout.addLayout(buttonsLayout, 5, 0, 1, 3)
        self.setLayout(mainLayout)

        self.setWindowTitle("Explore DICOM Files")
        self.resize(1200, 800)

    def browse(self):
        directory = QtWidgets.QFileDialog.getExistingDirectory(self, "Find Files",
                QtCore.QDir.currentPath())

        if directory:
            if self.directoryComboBox.findText(directory) == -1:
                self.directoryComboBox.addItem(directory)

            self.directoryComboBox.setCurrentIndex(self.directoryComboBox.findText(directory))
            self.find()

    @staticmethod
    def updateComboBox(comboBox):
        if comboBox.findText(comboBox.currentText()) == -1:
            comboBox.addItem(comboBox.currentText())

    def find(self):
        self.filesTable.setRowCount(0)

        path = self.directoryComboBox.currentText()

        self.updateComboBox(self.directoryComboBox)

        self.currentDir = QtCore.QDir(path)
        fileName = "*.dcm"
        files = self.currentDir.entryList([fileName],
                QtCore.QDir.Files | QtCore.QDir.NoSymLinks)

        self.showFiles(files)

    def showFiles(self, files):
        for fn in files:
            file = QtCore.QFile(self.currentDir.absoluteFilePath(fn))
            size = QtCore.QFileInfo(file).size()

            fileNameItem = QtWidgets.QTableWidgetItem(fn)
            fileNameItem.setFlags(fileNameItem.flags() ^ QtCore.Qt.ItemIsEditable)
            sizeItem = QtWidgets.QTableWidgetItem("%d KB" % (int((size + 1023) / 1024)))
            sizeItem.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)
            sizeItem.setFlags(sizeItem.flags() ^ QtCore.Qt.ItemIsEditable)

            row = self.filesTable.rowCount()
            self.filesTable.insertRow(row)
            self.filesTable.setItem(row, 0, fileNameItem)
            self.filesTable.setItem(row, 1, sizeItem)

        self.filesFoundLabel.setText("%d file(s) found (Double click on a file to open it)" % len(files))

    def createButton(self, text, member):
        button = QtWidgets.QPushButton(text)
        button.clicked.connect(member)
        return button

    def createComboBox(self, text=""):
        comboBox = QtWidgets.QComboBox()
        comboBox.setEditable(True)
        comboBox.addItem(text)
        comboBox.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                QtWidgets.QSizePolicy.Preferred)
        return comboBox

    def createFilesTable(self):
        self.filesTable = QtWidgets.QTableWidget(0, 2)
        self.filesTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.filesTable.setHorizontalHeaderLabels(("File Name", "Size"))
        self.filesTable.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
        self.filesTable.verticalHeader().hide()
        self.filesTable.setShowGrid(False)
        self.filesTable.cellActivated.connect(self.openFileOfItem)

    def displayDicomInformation(self, msg):
        infoDialog = QtWidgets.QDialog()
        layout = QtWidgets.QGridLayout(infoDialog)
        layout.addWidget(QtWidgets.QLabel(msg))
        infoDialog.setLayout(layout)
        infoDialog.setWindowTitle('Dicom tag information')
        infoDialog.show()
        infoDialog.exec_()

    def openFileOfItem(self, row, column):
        item = self.filesTable.item(row, 0)
        path = self.directoryComboBox.currentText() + "/" + item.text()
        dataset = pydicom.dcmread(path)

        all_tags = ''
        for elem in dataset:
            print(elem)
            tag = str(elem) + '\n'
            all_tags += tag

        self.displayDicomInformation(all_tags)

def run_main():
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.showMaximized()
    sys.exit(app.exec_())

if __name__ == '__main__':
    run_main()

It can also be found on my GitHub page.

Weekly tech report (07/16-07/22)

1. An overview of build systems (mostly for C++ projects)

How many build tools do you know? Which one is your favorite? The post has a nice compilation of various build tools that are used in practice.

2. 30 Bash Scripting Examples

A beginner’s tutorial on Bash programming. The post contains 30 examples that are simple and useful to use.

3. Linux history Command Tutorial for Beginners (8 Examples)

A short post that describes the command ‘history’ in Linux. ‘history’ is a very handy command line tool if you have to re-execute the commands (especially long one) that you have previously executed.

4. Qt Creator 4.7.0 released

A newer version of Qt Creator 4.7.0 is released that has Clang code model ON by default.

5. CppCast- Design Patterns in Modern C++ with Dmitri Nesteruk

This episode of CppCast discusses the Design Patterns in various languages like C#, C++ etc.

6. What is Conan?

I’ve not used Conan yet, but this seems to be an interesting and promising project. The Getting started guide can be a useful resource for playing around with Conan.

Weekly tech report (07/09-07/15)

1. OpenCV

OpenCV is one of the most popular Open Source Computer Vision Library. Following are some learning resources that are helpful to get started with OpenCV.

Learn OpenCV
The nice blog dedicated to OpenCV with lots of useful materials on OpenCV. The site also has a free course on “OpenCV for Beginners” that gives a quick introduction to OpenCV.

2. DLTK

DLTK, the Deep Learning Toolkit for Medical Imaging extends TensorFlow to enable deep learning of biomedical images. It provides specialty ops and functions, implementations of models, tutorials (as used in this blog) and code examples for typical applications.

GitHub page

3. Python robotics

Contains a collection of robotics algorithms written in Python.

4. Profiling memory usage on Linux with Qt Creator 4.7

This is an interesting blog post that describes profiling memory usage with Qt Creator’s Performance Analyzer in an easy and fast way that allows gaining important insights about our application’s memory usage.

5. CppCast – Episode 158

This episode of CppCast discusses the Future of 2D Graphics Proposal with Guy Davidson. More on this proposal and current status can be found in the following links:

The 2D Graphics TS

P0267 Reference Implementation
It contains a reference implementation of P0267: A proposal to Add 2D Rendering and Display to C++. I’ve not tried building the library yet, but this seems to be an interesting project to explore and learn lots of new C++ features in use.

Proposal P0267