UnaNancyOwen
8/2/2019 - 2:06 PM

Convert Image in Each-Formats of Azure Kinect using OpenCV

Convert Image in Each-Formats of Azure Kinect using OpenCV

cmake_minimum_required( VERSION 3.6 )

project( AzureKinect )
add_executable( AzureKinect util.h main.cpp )

set_property( DIRECTORY PROPERTY VS_STARTUP_PROJECT "AzureKinect" )

set( k4a_DIR "C:/Program Files/K4A/lib/cmake/k4a" CACHE PATH "Path to Azure Kinect SDK (K4A) config directory."  )
find_package( k4a REQUIRED )

set( OpenCV_DIR "C:/Program Files/opencv/build" CACHE PATH "Path to OpenCV config directory." )
find_package( OpenCV REQUIRED )

if( k4a_FOUND AND OpenCV_FOUND )
  include_directories( ${OpenCV_INCLUDE_DIRS} )
  target_link_libraries( AzureKinect ${OpenCV_LIBS} )
  target_link_libraries( AzureKinect k4a::k4a )
endif()
#include <iostream>
#include <k4a/k4a.h>
#include <k4a/k4a.hpp>
#include <opencv2/opencv.hpp>

// Include Converter Utility Header
#include "util.h"

int main( int argc, char* argv[] )
{
    try{
        // Get Connected Devices
        const int32_t device_count = k4a_device_get_installed_count();
        if( device_count == 0 )
        {
            throw k4a::error( "Failed to found device!" );
        }

        // Open Default Device
        k4a::device device = k4a::device::open( K4A_DEVICE_DEFAULT );

        // Start Cameras with Configuration
        k4a_device_configuration_t configuration = K4A_DEVICE_CONFIG_INIT_DISABLE_ALL;
        configuration.color_format             = K4A_IMAGE_FORMAT_COLOR_BGRA32;
        configuration.color_resolution         = K4A_COLOR_RESOLUTION_720P;
        configuration.depth_mode               = K4A_DEPTH_MODE_NFOV_UNBINNED;
        configuration.synchronized_images_only = true;
        device.start_cameras( &configuration );

        while( true ){
            // Get Capture
            k4a::capture capture;
            const bool result = device.get_capture( &capture, std::chrono::milliseconds( K4A_WAIT_INFINITE ) );
            if( !result ){
                break;
            }

            // Get Color Image
            k4a::image color_image = capture.get_color_image();
            cv::Mat color = k4a::get_mat( color_image );
            
            // Get Depth Image
            k4a::image depth_image = capture.get_depth_image();
            cv::Mat depth = k4a::get_mat( depth_image );
            
            // Get Infrared Image
            k4a::image infrared_image = capture.get_ir_image();
            cv::Mat infrared = k4a::get_mat( infrared_image );

            // Clear Handle
            color_image.reset();
            depth_image.reset();
            infrared_image.reset();
            capture.reset();

            // Show Image
            depth.convertTo( depth, CV_8U, -255.0 / 5000.0, 255.0 );
            infrared.convertTo( infrared, CV_8U, 0.5 );
            
            cv::imshow( "color", color );
            cv::imshow( "depth", depth );
            cv::imshow( "infrared", infrared );
            const int32_t key = cv::waitKey( 30 );
            if( key == 'q' ){
                break;
            }
        }

        // Close Device
        device.close();
        
        // Close Window
        cv::destroyAllWindows();
    }
    catch( const k4a::error& error ){
        std::cout << error.what() << std::endl;
    }

    return 0;
}
/*
 This is utility to that provides converter to convert k4a::image to cv::Mat.

 cv::Mat mat = k4a::get_mat( image );

 Copyright (c) 2019 Tsukasa Sugiura <t.sugiura0204@gmail.com>
 Licensed under the MIT license.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

#ifndef __UTIL__
#define __UTIL__

#include <vector>
#include <limits>

#include <k4a/k4a.h>
#include <k4a/k4a.hpp>
#include <opencv2/opencv.hpp>

namespace k4a
{
    cv::Mat get_mat( k4a::image& src, bool deep_copy = true )
    {
        assert( src.get_size() != 0 );

        cv::Mat mat;
        const int32_t width = src.get_width_pixels();
        const int32_t height = src.get_height_pixels();

        const k4a_image_format_t format = src.get_format();
        switch( format )
        {
            case k4a_image_format_t::K4A_IMAGE_FORMAT_COLOR_MJPG:
            {
                // NOTE: this is slower than other formats.
                std::vector<uint8_t> buffer( src.get_buffer(), src.get_buffer() + src.get_size() );
                mat = cv::imdecode( buffer, cv::IMREAD_ANYCOLOR );
                cv::cvtColor( mat, mat, cv::COLOR_BGR2BGRA );
                break;
            }
            case k4a_image_format_t::K4A_IMAGE_FORMAT_COLOR_NV12:
            {
                cv::Mat nv12 = cv::Mat( height + height / 2, width, CV_8UC1, src.get_buffer() ).clone();
                cv::cvtColor( nv12, mat, cv::COLOR_YUV2BGRA_NV12 );
                break;
            }
            case k4a_image_format_t::K4A_IMAGE_FORMAT_COLOR_YUY2:
            {
                cv::Mat yuy2 = cv::Mat( height, width, CV_8UC2, src.get_buffer() ).clone();
                cv::cvtColor( yuy2, mat, cv::COLOR_YUV2BGRA_YUY2 );
                break;
            }
            case k4a_image_format_t::K4A_IMAGE_FORMAT_COLOR_BGRA32:
            {
                mat = deep_copy ? cv::Mat( height, width, CV_8UC4, src.get_buffer() ).clone()
                                : cv::Mat( height, width, CV_8UC4, src.get_buffer() );
                break;
            }
            case k4a_image_format_t::K4A_IMAGE_FORMAT_DEPTH16:
            case k4a_image_format_t::K4A_IMAGE_FORMAT_IR16:
            {
                mat = deep_copy ? cv::Mat( height, width, CV_16UC1, reinterpret_cast<uint16_t*>( src.get_buffer() ) ).clone()
                                : cv::Mat( height, width, CV_16UC1, reinterpret_cast<uint16_t*>( src.get_buffer() ) );
                break;
            }
            case k4a_image_format_t::K4A_IMAGE_FORMAT_CUSTOM8:
            {
                mat = cv::Mat( height, width, CV_8UC1, src.get_buffer() ).clone();
                break;
            }
            case k4a_image_format_t::K4A_IMAGE_FORMAT_CUSTOM:
            {
                // NOTE: This is opencv_viz module format (cv::viz::WCloud).
                const int16_t* buffer = reinterpret_cast<int16_t*>( src.get_buffer() );
                mat = cv::Mat( height, width, CV_32FC3, cv::Vec3f::all( std::numeric_limits<float>::quiet_NaN() ) );
                mat.forEach<cv::Vec3f>(
                    [&]( cv::Vec3f& point, const int32_t* position ){
                        const int32_t index = ( position[0] * width + position[1] ) * 3;
                        point = cv::Vec3f( buffer[index + 0], buffer[index + 1], buffer[index + 2] );
                    }
                );
                break;
            }
            default:
                throw k4a::error( "Failed to convert this format!" );
                break;
        }

        return mat;
    }
}

cv::Mat k4a_get_mat( k4a_image_t& src, bool deep_copy = true )
{
    k4a_image_reference( src );
    return k4a::get_mat( k4a::image( src ), deep_copy );
}

#endif // __UTIL__