OpenCV se puede usar con los enlaces de python y funciona bastante bien. Sin embargo, me preguntaba (con la esperanza) si también es posible usar OpenCv's stitcher en python. Intenté varias cosas pero no pude hacer que funcionara. Si es posible, probablemente necesite hacer una importación adicional, pero no puedo resolverlo y Google tampoco me da la respuesta. Espero que haya un gurú de python abierto que pueda ayudarme.Usar el agrupador opencv de python
Respuesta
Bien, entonces, lo descubrí finalmente. Hasta ahora solo he portado el método de puntadas con dos argumentos, pregúntame si tienes problemas para exponer cualquier otra cosa que necesites.
La manera más fácil de compilarlo es compilando todo de una manera independiente de la posición (opción -fPIC para gcc) en una biblioteca dinámica, mientras se enlazan las bibliotecas opencv_core y opencv_stitching. También deberá agregar el directorio de inclusión para la versión de python con la que esté compilando, para que pueda encontrar el encabezado Python.h correcto.
Si compila correctamente, podrá usar la biblioteca compilada de la misma manera que usaría un módulo de python.
Desafortunadamente, dado que no proporcionan acceso al constructor, tuve que conformarme con hacer una instancia global del asunto. Si hay otra forma elegante, soy todo oídos (ojos). Esto significa que cada vez que llame al constructor .Stitcher() devolverá la misma instancia (hay una separada que intenta usar GPU durante la construcción, use .Stitcher (True) para eso).
Aquí está mi archivo pythonPort.h:
/*
* File: pythonPort.h
* Author: algomorph
*
* Created on December 5, 2012, 10:18 AM
*/
#ifndef PYTHONPORT_H
#define PYTHONPORT_H
#define MODULESTR "mycv"
#include "Python.h"
#include "numpy/ndarrayobject.h"
#include <opencv2/core/core.hpp>
#include <opencv2/stitching/stitcher.hpp>
/*
//include your own custom extensions here
#include "savgol.h"
#include "filters.hpp"
*/
#include "pythonPortAux.h"
#endif
MODULESTR debe ser lo que quiera el nombre de su módulo. Lo he mantenido igual que el nombre de la biblioteca que compila.
Deberá copiar las rutinas opencv_to y opencv_from que necesite del archivo cv2.cpp y colocarlas en algo como mi pythonPortAux.h. El mío tiene muchas rutinas a partir de ahí, puedes encontrarlo at this link. MKTYPE2 macro también está allí.
El resto está aquí en el archivo pythonPort.cpp abajo (tengo otras cosas que hay, esto es sólo la parte Stitcher relevante):
#include "pythonPort.h"
struct pycvex_Stitcher_t
{
PyObject_HEAD
Ptr<cv::Stitcher> v;
};
static PyTypeObject pycvex_Stitcher_Type =
{
PyObject_HEAD_INIT(&PyType_Type)
0,
MODULESTR".Stitcher",
sizeof(pycvex_Stitcher_t),
};
static void pycvex_Stitcher_dealloc(PyObject* self)
{
//((pycvex_Stitcher_t*)self)->v.release();
PyObject_Del(self);
}
static PyObject* pyopencv_from(const Ptr<cv::Stitcher>& r)
{
pycvex_Stitcher_t *m = PyObject_NEW(pycvex_Stitcher_t, &pycvex_Stitcher_Type);
new (&(m->v)) Ptr<cv::Stitcher>(); // init Ptr with placement new
m->v = r;
return (PyObject*)m;
}
static bool pyopencv_to(PyObject* src, Ptr<cv::Stitcher>& dst, const char* name="<unknown>")
{
if(src == NULL || src == Py_None)
return true;
if(!PyObject_TypeCheck(src, &pycvex_Stitcher_Type))
{
failmsg("Expected cv::Stitcher for argument '%s'", name);
return false;
}
dst = ((pycvex_Stitcher_t*)src)->v;
return true;
}
static PyObject* pycvex_Stitcher_repr(PyObject* self)
{
char str[1000];
sprintf(str, "<Stitcher %p>", self);
return PyString_FromString(str);
}
Stitcher gStitcher = cv::Stitcher::createDefault(false);
Stitcher gStitcherGPU = cv::Stitcher::createDefault(true);
static PyObject* pycvex_Stitcher_Stitcher(PyObject* , PyObject* args, PyObject* kw)
{
PyErr_Clear();
{
pycvex_Stitcher_t* self = 0;
bool try_use_gpu = false;
const char* keywords[] = { "img", "pt1", "pt2","connectivity","leftToRight", NULL };
if (PyArg_ParseTupleAndKeywords(args, kw, "|b:Stitcher",
(char**) keywords, &try_use_gpu)){
self = PyObject_NEW(pycvex_Stitcher_t, &pycvex_Stitcher_Type);
if (self)
ERRWRAP2(
if(try_use_gpu)
self->v = &gStitcherGPU;
else
self->v = &gStitcher;
);
return (PyObject*) self;
}
}
return NULL;
}
static PyGetSetDef pycvex_Stitcher_getseters[] =
{
{NULL} /* Sentinel */
};
static PyObject* pycvex_Stitcher_stitch(PyObject* self, PyObject* args, PyObject* kw){
if(!PyObject_TypeCheck(self, &pycvex_Stitcher_Type))
return failmsgp("Incorrect type of self (must be 'Stitcher' or its derivative)");
Stitcher* _self_ = ((pycvex_Stitcher_t*)self)->v;
//Stitcher::Status status;
int status;
PyObject* pyobj_images = NULL;
vector<Mat> images = vector<Mat>();
Mat pano;
const char* keywords[] = { "images", NULL };
if(PyArg_ParseTupleAndKeywords(args, kw, "O:Stitcher.stitch", (char**)keywords, &pyobj_images) &&
pyopencv_to(pyobj_images, images, ArgInfo("images", false)))
{
ERRWRAP2(status = (int)_self_->stitch(images, pano));
return Py_BuildValue("(NN)", pyopencv_from(status), pyopencv_from(pano));
}
return NULL;
}
static PyMethodDef pycvex_Stitcher_methods[] =
{
{"stitch", (PyCFunction)pycvex_Stitcher_stitch, METH_KEYWORDS, "stitch(image) -> status, pano"},
{NULL, NULL}
};
static void pycvex_Stitcher_specials(void)
{
pycvex_Stitcher_Type.tp_base = NULL;
pycvex_Stitcher_Type.tp_dealloc = pycvex_Stitcher_dealloc;
pycvex_Stitcher_Type.tp_repr = pycvex_Stitcher_repr;
pycvex_Stitcher_Type.tp_getset = pycvex_Stitcher_getseters;
pycvex_Stitcher_Type.tp_methods = pycvex_Stitcher_methods;
}
static PyMethodDef methods[] = {
{"Stitcher",(PyCFunction)pycvex_Stitcher_Stitcher, METH_KEYWORDS, "Stitcher([tryUseGpu=False]) -> <Stitcher object>"},
{NULL, NULL}
};
extern "C"{
#if defined WIN32 || defined _WIN32
__declspec(dllexport)
#endif
void initcvex()
{
MKTYPE2(Stitcher);
import_array();
PyObject* m = Py_InitModule(MODULESTR, methods);
PyObject* d = PyModule_GetDict(m);
//PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION))
opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
PyDict_SetItemString(d, "error", opencv_error);
}
}
Parece que esto podría ser útil, pero me estoy metiendo en problemas. ¿Dónde están 'filters.hpp' y' savgol.h'? También recibo errores con respecto a 'python27_d.lib'. ¿Alguna sugerencia? – speedplane
Lo sentimos, no los necesita (filters.hpp y savgol.h). Estos fueron solo por extensiones que agregué a opencv, para la detección de bordes de Berkley. Los comenté desde el código anterior. –
En cuanto a python27_d.lib, este problema surge en las plataformas de Windows cuando intenta compilar algo que hace referencia a opencv en el modo de depuración. Para una instalación típica de Windows Python, esta biblioteca no está incluida. Puede reconfigurar manualmente el proyecto de enlaces de python de opencv para usar python2.lib o intentar y hacer referencia a la versión de lanzamiento en su lugar. Si realmente desea usarlo, consulte esta publicación SO: http://stackoverflow.com/questions/10315662/how-to-obtain-pre-built-debug-version-of-python-library-eg-python27 -d-dll –
- 1. Error al usar knnMatch con OpenCV + Python
- 2. Implementación Python OpenCV SVM
- 3. ¿Usar ROI en OpenCV?
- 4. Python OpenCV Box2D
- 5. OpenCV 2.0 y Python
- 6. ¿Debo dejar de usar OpenCV?
- 7. opencv macport python bindings
- 8. Python: Urllib2 y OpenCV
- 9. Enlaces de OpenCV Python para el algoritmo de GrabCut
- 10. Cómo usar opencv flann :: Index?
- 11. Dibujando histograma en OpenCV-Python
- 12. Cómo instalar OpenCV para python
- 13. OpenCV PCA Compute en Python
- 14. Libros para OpenCV y Python?
- 15. ¿Qué versión de python opencv debo elegir?
- 16. FileStorage para OpenCV Python API
- 17. Python OpenCV Jerarquía de árbol de contorno
- 18. OpenCV Python e histograma de gradiente orientado
- 19. OpenCV 2.4 en python - Procesamiento de video
- 20. Grabación de video con OpenCV + Python + Mac
- 21. Problemas en el uso de cámaras web en Python + OPENCV
- 22. Características de OpenCV Python y SIFT
- 23. Comprobando el área del contorno en opencv usando python
- 24. Ejecutando OpenCV desde un Python virtualenv
- 25. Cómo usar cv :: BackgroundSubtractorMOG en OpenCV?
- 26. ¿Usar la jerarquía en findContours() en OpenCV?
- 27. OpenCV: IplImage versus Mat, ¿cuál usar?
- 28. CGBitmapContextCreate para CV_8UC3 (para usar en OpenCV)
- 29. ¿Cómo rastreo el movimiento usando OpenCV en Python?
- 30. Cargando un video en OpenCV en Python
Oye, sé que es probablemente un poco tarde para ti, pero estoy en posición ahora cuando quiero usar el Stitch de Opencv con Python. Me he dado cuenta de cómo portar otras clases de opencv "faltantes" de la API de python de opencv, y lo he hecho antes. Si termino exponiendo Stitcher a Python, lo tendré hasta el final de hoy. –