Need help converting from Python api to C api [closed]
I need to download an image and measure it's contrast. I have some Python code which does what I need, but now I need to convert it to C, so that I can use it from other languages which do not have OpenCV bindings. This is the Python version:
import cv2
import numpy as np
nparr = np.asarray(bytearray(image_file_in_memory), dtype=np.uint8)
img = cv2.imdecode(nparr, 0)
height, width, depth = img.shape
roi = img[0:bottom, 0:right]
edges = cv2.Sobel(roi, -1, 1, 1)
count = np.sum(edges);
This is what I have so far. But I can't get the pixel count to tally properly. It always returns the value height x width, instead of only the count of white pixels, like the Python version does.
int count = 0;
IplImage *img, *tmp;
CvMat *mat = cvCreateMat(1, src_len, CV_8SC1);
/* src is the in-memory image */
mat->data.ptr = (unsigned char *)src;
img = cvDecodeImage(mat, -1);
if (! img) return -1;
cvReleaseMat(&mat);
cvSetImageROI(img, cvRect(0, 0, right, bottom));
tmp = cvCloneImage(img);
cvSobel(img, tmp, 1, 1, 3);
count = cvCountNonZero(tmp);
/* or */
count = cvSum(tmp).val[0];
Just wondering, is it important that you use the C variant? Or is the C++ variant possible also? The C - interface is absolete and will vanish in future releases. So better to switch to the C++ variant immediatly.
I am restricted to using C.
I wonder why is there such a resistance to just making the C interface up-to-date. Is it not clear that C is the only way to interop for the majority of languages? Even for many of the "official" wrappers a "C" interface had to be made... why keep replicating the effort when you could just automatically generate a common C interface (related issue)?
I guess it is evolution? It is the same as why would you still use horse and carriage if you can use a car ...
@StevenPuttemans I'm afraid I missed your point entirely. The fact that C++ is not a good interop language is not evolution. It has to do with not having a standard ABI and making extensive use of textual preprocessors. C has none of these complications and that's why it's the only interop language supported natively by Go, Ruby, D, C#, Lua, ... every single wrapper is replicating its own C API because there is simply no way to interface with C++. I'm not saying people should go back to coding native OpenCV in C, so please keep these two issues separate. I'm simply stating that OpenCV is a powerful interface for computer vision that is wanted and needed on many languages. Why make it harder by not having an automatically generated C interface?