logo
down
shadow

polarToCart and cartToPolar functions in opencv


polarToCart and cartToPolar functions in opencv

By : jschwuchow
Date : November 22 2020, 01:01 AM
To fix this issue if you're using opencv3, you probably want linearPolar:
note, that for both versions, you need a seperate src and dst image (does not work inplace)
code :
#include "opencv2/opencv.hpp"  // needs imgproc, imgcodecs & highgui

Mat src = imread("my.png", 0); // read a grayscale img
Mat dst; // empty.
linearPolar(src,dst, Point(src.cols/2,src.rows/2), 120, INTER_CUBIC );
imshow("linear", dst);
waitKey();
logPolar(src,dst,Point(src.cols/2,src.rows/2),40,INTER_CUBIC );
Mat src=...;
Mat dst(src.size(), src.type()); // yes, you need to preallocate here

IplImage ipsrc = src; // new header, points to the same pixels
IplImage ipdst = dst;


cvLogPolar( &ipsrc, &ipdst, cvPoint2D32f(src.cols/2,src.rows/2), 40, CV_INTER_CUBIC);

// result is in dst, no need to release ipdst (and please don't do so.)


Share : facebook icon twitter icon
Call C++ opencv functions from Python ( Send a cv :: Mat to C++ dll which is using opencv )

Call C++ opencv functions from Python ( Send a cv :: Mat to C++ dll which is using opencv )


By : Ari Gonzalez
Date : March 29 2020, 07:55 AM
I wish this help you You can have a look at the OpenCV Python wrapper. In the OpenCV folder in modules/python/src2/cv2.cpp (depending on the version, I use OpenCV 2.4) there are some functions called pyopencv_to used by the OpenCV Python wrapper. One of those is used to convert PyObject to cv::Mat. Your "FromPython" function needs to get PyObject as input. I personally use boost::python::object to pass the numpy arrays returned by the Python OpenCV functions to the C++ function/class. You should end up having something like this in C++:
code :
///PythonToOCV.h

#ifndef __PYTHONTOOCV_H_INCLUDED__
#define __PYTHONTOOCV_H_INCLUDED__

#include <iostream>
#include <Python.h>
#include <boost/python.hpp>
#include "numpy/ndarrayobject.h"
#include "opencv2/core/core.hpp"

/////////////////////////////////////////////////////////////////////////////
/// \brief Import Numpy array. Necessary to avoid PyArray_Check() to crash
void doImport( );

int failmsg( const char *fmt, ... );

static size_t REFCOUNT_OFFSET = ( size_t )&((( PyObject* )0)->ob_refcnt ) +
( 0x12345678 != *( const size_t* )"\x78\x56\x34\x12\0\0\0\0\0" )*sizeof( int );

static inline PyObject* pyObjectFromRefcount( const int* refcount )
{
return ( PyObject* )(( size_t )refcount - REFCOUNT_OFFSET );
}

static inline int* refcountFromPyObject( const PyObject* obj )
{
return ( int* )(( size_t )obj + REFCOUNT_OFFSET );
}

class NumpyAllocator : public cv::MatAllocator
{
public:
NumpyAllocator( ) { }
~NumpyAllocator( ) { }

void allocate( int dims, const int* sizes, int type, int*& refcount,
uchar*& datastart, uchar*& data, size_t* step );

void deallocate( int* refcount, uchar* datastart, uchar* data );
};


/////////////////////////////////////////////////////////////////////////////
/// \brief Convert a numpy array to a cv::Mat. This is used to import images
/// from Python.
/// This function is extracted from opencv/modules/python/src2/cv2.cpp
/// in OpenCV 2.4
int pyopencv_to( const PyObject* o, cv::Mat& m, const char* name = "<unknown>", bool allowND=true );
#endif //__PYTHONTOOCV_H_INCLUDED__

///PythonToOCV.cpp

#include "PythonToOpenCV.h"

void doImport( )
{
    import_array( );
}

int failmsg( const char *fmt, ... )
{
    char str[1000];

    va_list ap;
    va_start( ap, fmt );
    vsnprintf( str, sizeof( str ), fmt, ap );
    va_end( ap );
    PyErr_SetString( PyExc_TypeError, str );
    return 0;
}

void NumpyAllocator::allocate( int dims, const int* sizes, int type, int*& refcount, uchar*& datastart, uchar*& data, size_t* step )
{
    int depth = CV_MAT_DEPTH( type );
    int cn = CV_MAT_CN( type );
    const int f = ( int )( sizeof( size_t )/8 );
    int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
                  depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
                  depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
                  depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
    int i;
    npy_intp _sizes[CV_MAX_DIM+1];
    for( i = 0; i < dims; i++ )
        _sizes[i] = sizes[i];
    if( cn > 1 )
    {
    /*if( _sizes[dims-1] == 1 )
         _sizes[dims-1] = cn;
    else*/
        _sizes[dims++] = cn;
    }
    PyObject* o = PyArray_SimpleNew( dims, _sizes, typenum );
    if( !o )
    CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
    refcount = refcountFromPyObject(o);
    npy_intp* _strides = PyArray_STRIDES(o);
    for( i = 0; i < dims - (cn > 1); i++ )
        step[i] = (size_t)_strides[i];
    datastart = data = (uchar*)PyArray_DATA(o);

}

void NumpyAllocator::deallocate( int* refcount, uchar* datastart, uchar* data )
{
    if( !refcount )
       return;
    PyObject* o = pyObjectFromRefcount(refcount);
    Py_INCREF(o);
    Py_DECREF(o);
}

// Declare the object
NumpyAllocator g_numpyAllocator;

int pyopencv_to(const PyObject* o, cv::Mat& m, const char* name, bool allowND )
{
    // to avoid PyArray_Check() to crash even with valid array
    doImport( );

    if(!o || o == Py_None)
    {
        if( !m.data )
            m.allocator = &g_numpyAllocator;
        return true;
    }

    if( !PyArray_Check(o) )
    {
        failmsg("%s is not a numpy array", name);
        return false;
    }

    // NPY_LONG (64 bit) is converted to CV_32S (32 bit)
    int typenum = PyArray_TYPE(o);
    int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S :
        typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S :
        typenum == NPY_INT || typenum == NPY_LONG ? CV_32S :
        typenum == NPY_FLOAT ? CV_32F :
        typenum == NPY_DOUBLE ? CV_64F : -1;

    if( type < 0 )
    {
        failmsg("%s data type = %d is not supported", name, typenum);
        return false;
    }

    int ndims = PyArray_NDIM(o);
    if(ndims >= CV_MAX_DIM)
    {
        failmsg("%s dimensionality (=%d) is too high", name, ndims);
        return false;
    }

    int size[CV_MAX_DIM+1];
    size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type);
    const npy_intp* _sizes = PyArray_DIMS(o);
    const npy_intp* _strides = PyArray_STRIDES(o);
    bool transposed = false;

    for(int i = 0; i < ndims; i++)
    {
        size[i] = (int)_sizes[i];
        step[i] = (size_t)_strides[i];
    }

    if( ndims == 0 || step[ndims-1] > elemsize ) {
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }

    if( ndims >= 2 && step[0] < step[1] )
    {
        std::swap(size[0], size[1]);
        std::swap(step[0], step[1]);
        transposed = true;
    }

    if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] )
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }

    if( ndims > 2 && !allowND )
    {
        failmsg("%s has more than 2 dimensions", name);
        return false;
    }

    m = cv::Mat(ndims, size, type, PyArray_DATA(o), step);

    if( m.data )
    {
        m.refcount = refcountFromPyObject(o);
        m.addref(); // protect the original numpy array from deallocation
        // (since Mat destructor will decrement the reference counter)
    };
    m.allocator = &g_numpyAllocator;

    if( transposed )
    {
        cv::Mat tmp;
        tmp.allocator = &g_numpyAllocator;
        transpose(m, tmp);
        m = tmp;
    }
    return true;
}
/// fromPython.h

#ifndef __FROMPYTHON_H_INCLUDED__
#define __FROMPYTHON_H_INCLUDED__

#include "PythonToOCV.h"
#include <boost/python.hpp>

int fromPython( boost::python::object &frame );
#endif //__FROMPYTHON_H_INCLUDED__



/// fromPython.cpp

#include "fromPython.h"

int fromPython( boost::python::object &frame )
{
     cv::Mat image;
     // this is the function from modules/python/src2/cv2.cpp (the third parameter might be ArgInfo in later OpenCV versions)
     pyopencv_to( frame.ptr( ), image, "info", true );

     ///
     ///  HERE code using cv::Mat image          
     ///

     return 1;
} 
#include "fromPython.h"
using namespace boost::python; 

/// This function needs to be included to pass PyObjects as numpy array ( http://mail.python.org/pipermail/cplusplus-sig/2006-September/011021.html )
void* extract_pyarray( PyObject* x )
{
    return PyObject_TypeCheck( x, &PyArray_Type ) ? x : 0;
}

BOOST_PYTHON_MODULE( myWrapper )
{
     // This function needs to be included to pass PyObjects as numpy array ( http://mail.python.org/pipermail/cplusplus-sig/2006-September/011021.html )
     boost::python::converter::registry::insert( &extract_pyarray, type_id<PyArrayObject>( ) ); 
     def fromPython( "fromPython", &fromPython );
} 
import myWrapper
import cv2 

def myFunct():
    cap = cv2.VideoCapture(0)
    while(1):
        ret,frame = cap.read()
        myWrapper.fromPython(frame)
Putting a vector of points through cartToPolar in OpenCV

Putting a vector of points through cartToPolar in OpenCV


By : PFault
Date : March 29 2020, 07:55 AM
Any of those help Since cv::Mat has a constructor with a data pointer and a step, you can make two as containers for the interleaved x and y components of each Point2f in the vector, which has contiguous data.
Code
code :
#include "opencv2/opencv.hpp"

int main(int argc,const char* argv[])
{
    std::vector<cv::Point2f> sides;
    sides.push_back(cv::Point2f(3, 4));
    sides.push_back(cv::Point2f(6, 8));
    sides.push_back(cv::Point2f(1, 1));

    cv::Mat xpts(sides.size(), 1, CV_32F, &sides[0].x, 2 * sizeof(float));
    cv::Mat ypts(sides.size(), 1, CV_32F, &sides[0].y, 2 * sizeof(float));

    std::cout << "x: " << xpts.t() << std::endl;
    std::cout << "y: " << ypts.t() << std::endl;

    cv::Mat magnitude, angle;
    cv::cartToPolar(xpts, ypts, magnitude, angle);

    std::cout << "\nmagnitude: " << magnitude.t();
    std::cout << "\nangle: " << angle.t() *180. / CV_PI << std::endl;
    return 0;
}
x: [3, 6, 1]
y: [4, 8, 1]

magnitude: [5, 10, 1.4142135]
angle: [53.136284, 53.136284, 44.990456]
Cannot find OpenCV 2 Delaunay triangulation functions in OpenCV 3

Cannot find OpenCV 2 Delaunay triangulation functions in OpenCV 3


By : john lester Odra
Date : March 29 2020, 07:55 AM
wish help you to fix your issue cvCreateSubdivDelaunay2D became legacy (so does the whole c-interface for delauny triangulation) and has been removed. For OpenCV 3 you can refer to the cv::SubDiv class instead.
cartToPolar returns not enough distinct angles

cartToPolar returns not enough distinct angles


By : Grace Hernander
Date : March 29 2020, 07:55 AM
I hope this helps . You have two binary images (sobel_x_bin and sobel_y_bin) which you use as x and y components of the gradient at each pixel. Therefore, each pixel can only have four distinct gradient vectors, with only three different angles:
code :
cvtColor(frame, frame, COLOR_BGR2GRAY);
GaussianBlur(frame, gauss, Size(gauss_size, gauss_size), 2.0);

Sobel(gauss, sobel_x, CV_32F, 1.0, 0.0, 3);
Sobel(gauss, sobel_y, CV_32F, 0.0, 1.0, 3);
cartToPolar(sobel_x, sobel_y, gradient, angle, true);
Precision lost calling cv2.cartToPolar with angleInDegrees set to False

Precision lost calling cv2.cartToPolar with angleInDegrees set to False


By : user3015873
Date : March 29 2020, 07:55 AM
To fix the issue you can do It's an interesting observation. This must have to do with the precision of floating point arithmetic as pointed out by @Sushi. As per the documentation here, the output of cv2.cartToPolar function is given by
code :
x = np.asarray([[-12]], dtype = "float32")
y = np.asarray([[0]], dtype = "float32")

print(cv2.cartToPolar(x, y, angleInDegrees=False)[1])
print(np.radians(np.arctan2(y, x) * 180 / np.pi))

x = np.asarray([[-12]], dtype = "float64")
y = np.asarray([[0]], dtype = "float64")

print(cv2.cartToPolar(x, y, angleInDegrees=False)[1])
print(np.radians(np.arctan2(y, x) * 180 / np.pi))  
[[3.1415927]]
[[3.1415927]]
[[3.14159274]]
[[3.14159265]]  # check this result
Related Posts Related Posts :
  • What is the purpose of name mangling in C++?
  • C++ Why the void function is not working eventhough I called it?
  • How the pointer and the pointer's adress can share the same memory adress?
  • error C2220: warning treated as error - no 'object' file generated
  • exception of strcpy function in c++ console program
  • How to access USB barcode scanner data directly from USB port using C/C++ without driver
  • Under which circumstances will std::vector.clear() call a destructor?
  • Template partial specialisation and dependent names
  • best way to share data between c codes
  • C++ ignores if statement conditions
  • How to set the argv[ ] to be case-insensitive in a Win32 Console Application?
  • How to fix error "clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)"?
  • C++ How do I print a .txt file verbatim?
  • Creating two dimensional array of class
  • How do I correctly use COMMTIMEOUTS with OVERLAPPED IO mode reading from a Serial port
  • An assert macro which expands to static_assert when possible?
  • How to write a copyconstructor for a class which has HANDLE as a member in win32 c++ application?
  • C++ saving info such as tree in a file
  • Transforming an expression template tree
  • How to overload an operator with multiple parameters like a + b + c?
  • C++ 11 with Raspberry Pi performances
  • Make a C++ class look like a numpy array using swig
  • Postfix incrementer overloading for nested enumerated types
  • Is there a tidy way of associating metadata with functions in C++
  • QObject::installEventFilter(): Cannot filter events for objects in a different thread
  • LNK2005 error with Zxing C++
  • C++ Doubly Linked List with Pointers: Object of class isn't constructed properly
  • Using a random string generator in c++ constructor
  • What should I use instead of void as one of the alternative types in an variant?
  • C++ return value from multithreads using reference
  • How to connect multiple TCP IP clients to same server port using c++
  • Defaul compiler generates the reference operator (In C++)?
  • Unable to change directory time stamp after using FILE_FLAG_BACKUP_SEMANTICS
  • vector handling displaying output
  • WSAGetLastError returns WSAENOTSOCK - Cause?
  • C++: How to overload pow for user type?
  • C++ using arrays as multidimensional despite initalising it as 1D with pointer
  • How negate std::is_integral for use in tag dispatch?
  • Retrieve serial number from USB memory (Windows environment c++)
  • g++ error: invalid preprocessing directive #INCLUDE
  • C++ What is the std::for_each() function parameter type?
  • C++: Read individual lines from text file, sort words alphabetically
  • Saving 'this' address into a variable
  • c++ command line arguments in ubuntu terminal
  • Convert "Cartesian coordinates" to "polar coordinates with respect to user specified origin"
  • In what order are local scoped objects destructed?
  • How to use SDL_MapRGB with SDL 2.0
  • how compiler and interpreter work in case of array declaration
  • GSL integration behaves strange
  • Cropping an image with OpenCV and C
  • Find the last line in text file and select the first 10 char and print to a new file?
  • Created many CCSprits but when triggering ccTouchBegan gives the last one allways
  • seekp and seekg don't work with fstream
  • Taking input in Sublime Text 3
  • ld: -bind_at_load and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together
  • C++ storing #define as std::string would give size as zero compile time
  • How to use static linking with OpenSSL in C/C++
  • What is the difference between a trap, an error, a failure and program abortion?
  • Dynamic members allocation in qt
  • How to reduce object file size when compiling for VxWorks 5.5.1?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org