Limit Zbar to QR code only in Python - python

I'm using Zbar with it's Processor option in Python. I've been trying to figure out how to limit the symbology to QR-code only, but have only found answers for C as it follows:
scanner = new ImageScanner();
scanner.setConfig(Symbol.QRCODE, Config.ENABLE, 1);
I understand that the original code is written for C but is there anyway to do it in Python? Python isn't my main language and it's a bit difficult for me to understand what the arguments are in this case for processor.parse_config() (which I have currently set to 'enable'):
From https://github.com/npinchot/zbar/blob/master/processor.c
static PyObject*
processor_parse_config (zbarProcessor *self,
PyObject *args,
PyObject *kwds)
{
const char *cfg = NULL;
static char *kwlist[] = { "config", NULL };
if(!PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &cfg))
return(NULL);
if(zbar_processor_parse_config(self->zproc, cfg)) {
PyErr_Format(PyExc_ValueError, "invalid configuration setting: %s",
cfg);
return(NULL);
}
Py_RETURN_NONE;
}
I don't even understand why 'enable' is a valid argument.

Took me some time to figure this out since there's no documentation and the config format is counter-intuitive, IMO, but here you go:
proc.parse_config('disable')
proc.parse_config('qrcode.enable')
The first line, disable, disables all scanners.
The second line enables the qrcode scanner.

Related

Communicate C++ program with Arduino through Python

I'm been struggling with this problem pretty long. I have to communicate with an Arduino and C++ program. I know it is easy in Python, but it has to be in C++ for school project. So I'm reading a lot of things, but no one help me further.
So I have a short Python script that communicate with the arduino very well and fast written in Python.
communication.py:
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
def communicate(number):
ser.write(number)
return ser.readline()
The Arduino gets the number and returns values of light sensors in a string. Now I want this to communicate with C++ program. My C++ code (this is only a small part of the full program)
mainwindow.cpp:
void MainWindow::run(){
while (ui->startstop->value() == 1){// as long that the program must run
blockchange = 0;
// get data from arduino
Py_Initialize();
const char* modulename = "communication";
PyObject *pName = PyUnicode_FromString(modulename);
PyObject *pModule = PyImport_Import(pName);
if (pModule != NULL){
PyObject *pDict = PyModule_GetDict(pModule);
PyObject *pFunc = PyDict_GetItem(pDict, PyUnicode_FromString("communicate"));
if (pFunc != NULL){
PyObject_CallObject(pFunc, PyLong_FromLong(blockchange));
}else{
std::cout << "couldn't find func\n";
}
}else{
std::cout << "pyhton module not found\n";
}
}
It only gives "python module not found". Which means that PyImport_Import(pName) returns NULL. What is wrong?
I use Ubuntu 18.04 and my standard version of Python is 3.5 and the program is written in Qt Creator. I tried a lot of things, also without Python, but I haven't found anything that works. I only want that my Arduino reads one int from 0 to 6, and that the C++ program reads a string of 6 numbers separated with a ",".

Is it C++ for loop had require run time?

I had one c++ program that inside for loop, calling a function.
The function is doing a heavy process, it is embedded with python and performing image processing.
My question is, why can it only run at the first instance of the variable?
Main function (I only show the part of code require in this title):
int main(){
for(int a = 0;a<5;a++){
for(int b=0;b<5;b++){
// I want every increment it go to PyRead() function, doing image processing, and compare
if(PyRead()==1){
// some application might be occur
}
else {
}
}
}
PyRead() function, the function in c++ to go into python environment performing image processing:
bool PyRead(){
string data2;
Py_Initialize();
PyRun_SimpleString("print 'hahahahahawwwwwwwwwwwww' ");
char filename[] = "testcapture";
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
PyObject * moduleObj = PyImport_ImportModule(filename);
if (moduleObj)
{
PyRun_SimpleString("print 'hahahahaha' ");
char functionName[] = "test";
PyObject * functionObj = PyObject_GetAttrString(moduleObj, functionName);
if (functionObj)
{
if (PyCallable_Check(functionObj))
{
PyObject * argsObject = PyTuple_New(0);
if (argsObject)
{
PyObject * resultObject = PyEval_CallObject(functionObj, argsObject);
if (resultObject)
{
if ((resultObject != Py_None)&&(PyString_Check(resultObject)))
{
data2 = PyString_AsString(resultObject);
}
Py_DECREF(resultObject);
}
else if (PyErr_Occurred()) PyErr_Print();
Py_DECREF(argsObject);
}
}
Py_DECREF(functionObj);
}
else PyErr_Clear();
Py_DECREF(moduleObj);
}
Py_Finalize();
std::cout << "The Python test function returned: " << data2<< std::endl;
cout << "Data2 \n" << data2;
if(compareID(data2) == 1)
return true;
else
return false;
}
This is second time I ask this question in stack overflow. I hope this time this question will be more clear!
I can successful compile with no error.
When I run the program, I realize at a=0, b=0 it will go to PyRead() function and return value, after that it go to a=0, b=1, at that moment the whole program will end.
It supposes to go to PyRead() function again, but it does not do that and straight ending the program.
I must strongly mention that PyRead() function needed a long time to run (30seconds).
I had no idea what happens, seeking for somehelp. Please focus on the Bold part to understand my question.
Thanks.
See the comment in https://docs.python.org/2/c-api/init.html#c.Py_Finalize
Ideally, this frees all memory allocated by the Python interpreter.
Dynamically loaded extension modules loaded by Python are not unloaded.
Some extensions may not work properly if their initialization routine is called more than once
It seems your module, does not play well with this function.
A workaround can be - create the script on the fly and call it with python subprocess.

Best Practices for Calling Scipy From C

I've written some C-code to call scipy functions. The body, including variable declarations and using EXIT FAIL to denote messages and cleanup steps, is:
PyObject *module_name, *module = NULL;
PyObject *funct = NULL;
PyObject *output = NULL;
int j;
double dInVal, dOutVal;
Py_Initialize();
module_name = PyString_FromString("scipy.stats");
module = PyImport_Import(module_name);
Py_DECREF(module_name);
if (!module)
EXIT FAIL
funct = PyObject_GetAttrString(module, "beta");
if (!funct)
EXIT FAIL
Py_DECREF(module);
for (j=0; j<=10; j++)
{
dInVal = (double)j/10.0;
output = PyObject_CallMethod(funct, "ppf", "(f,f,f)", dInVal, 50.0, 50.0);
if (!output)
EXIT FAIL
dOutVal = PyFloat_AsDouble(output);
Py_DECREF(output);
printf("%6.3f %6.3f\n", dInVal, dOutVal);
}
Py_DECREF(funct);
Py_Finalize();
When I run this as the main routine, it appears to work fine. However, when I run it as a subroutine, it works for a first call, but fails on any subsequent call.
The code does work as a subroutine after the first call, if I make all of the PyObject pointers static (and include the appropriate flags, so that Python is initialized and the "beta" object is imported only once), but make-everything-static seems like a brute force solution to the problem, especially if the program will eventually include more than one subroutine that calls Python.
My question is, what is the best practice for setting up a C-program, to call scipy from a subroutine?

Is Python open(file,vr) supposed to update atime?

Whenever I open() a file with Python, the last access time is not updated, that's very odd :
If I open with r/rb nothing changes if I stat the file
If I open with w/r+ or a the ctime and mtime update properly but not atime
It doesn't look like it is a filesystem problem (which is ext3 in this case) because if I touch or cat the file it does update properly.
I haven't been able to find a lot of information about it; is it supposed to behave this way or is there something wrong?
Please try running mount, and see, if noatime flag is used on the mounted fs. Also, if your kernel is fresh enough, it's the "relatime" that is set by-default.
The "open()" code is pretty self-explanatory and does not mess with ATIME flags:
/* >> fileutils.c from Python 3.2.3 */
FILE*
_Py_fopen(PyObject *path, const char *mode)
{
#ifdef MS_WINDOWS
wchar_t wmode[10];
int usize;
usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
if (usize == 0)
return NULL;
return _wfopen(PyUnicode_AS_UNICODE(path), wmode);
#else
FILE *f;
PyObject *bytes = PyUnicode_EncodeFSDefault(path);
if (bytes == NULL)
return NULL;
/* >> Plain fopen(), nothing fancy here. */
f = fopen(PyBytes_AS_STRING(bytes), mode);
Py_DECREF(bytes);
return f;
#endif
}

I want to embed Python to MVC application, by linking dynamically to python

I want to embed Python to m vc application, by linking dynamically to Python.
hModPython = AfxLoadLibrary("Python23.dll");
pFnPyRun_SimpleString *pFunction = NULL;
pFnPy_Initialize *pPy_Initialize = NULL;
pFunction = (pFnPyRun_SimpleString *)::GetProcAddress(hModPython, "PyRun_SimpleString");
pPy_Initialize = (pFnPy_Initialize *)::GetProcAddress(hModPython, "Py_Initialize");
try
{
pPy_Initialize();
if ( pFunction )
{
(*pFunction)("import sys"); // call the code
}
else
{
AfxMessageBox("unable to access function from python23.dll.", MB_ICONSTOP|MB_OK);
}
}
catch(...)
{
}
And then I want to execute a Python script through my MFC application -
HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwSize = GetFileSize(hFile, NULL);
DWORD dwRead;
char *s = new char[dwSize +1];
ReadFile(hFile, s, dwSize, &dwRead, NULL);
s[dwSize] = '\0';
CString wholefile(s);
wholefile.Remove('\r');
wholefile+="\n";
CloseHandle(hFile);
pFnPy_CompileString *pFPy_CompileString = (pFnPy_CompileString *)::GetProcAddress(hModPython, "Py_CompileString");
CString fl(file);
PyObject* pCodeObject = pFPy_CompileString(wholefile.GetBuffer(0), fl.GetBuffer(0), Py_file_input);
if (pCodeObject != NULL)
{
pFnPyEval_EvalCode *pFPyEval_EvalCode = (pFnPyEval_EvalCode *)::GetProcAddress(hModPython, "PyEval_EvalCode");
PyObject* pObject = pFPyEval_EvalCode((PyCodeObject*)pCodeObject, m_Dictionary, m_Dictionary);
}
I am facing two problems here , I want to link to Python dynamically and also make my vc application independent of the location on which Python is installed on the users machine. However , I am required to include python.h for my code to compile the following declaration.
PyObject* pCodeObject
Is there a workaround for this ? Or do I have to specify the include for "Python.h" ? Which would mean again the program becomes path dependent.
I tried copying some of the python definitions including PyObject into a header in my mfc app. Then it complies fine. but Py_CompileString call fails. so finally I am unable to run script from my MFC application by linking to python dynamically.
How can this be done ? Please help. Is there a different approach to linking to python dynamically. Please could you write to me ?
What you are doing is quite triky... I don't understand the problem with Python.h. It is needed only for compiling your program, not for running it. Surely you do not need it to be compile-time-path-independent, do you?
Anyway, you may get rid of the PyObject* definition simply by replacing it with void*, because they are binary compatible types. And it looks like you don't care too much about the type safety of your solution.
I'd say that the reason why your Py_CompileString fails may be because you have an error in your script, or something. You should really look into the raised python exception.

Categories

Resources