Wrapping an opencv implementaion of an error level analysis algorithm using cython

2024/11/15 9:32:45

i have implemented an error level analysis algorithm using c++(opencv version 2.4) and i want to build a python wrapper for it using cython. I have read some part of the documentation of cython for c++ but it did not help me and moreover i did not find any extra information for implementing the wrapper online. It would be really great if someone could guide me and help me solve this problem.

This is my code for which i want to build a pyhton wrapper:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <vector> // Control
int scale = 15,
quality = 75;// Image containers
cv::Mat input_image,
compressed_image;void processImage(int, void*)
{// Setting up parameters and JPEG compression
std::vector<int> parameters;
parameters.push_back(CV_IMWRITE_JPEG_QUALITY);
parameters.push_back(quality);
cv::imwrite("lena.jpeg", input_image, parameters);// Reading temp image from the disk
compressed_image = cv::imread("lena.jpeg");if (compressed_image.empty())
{std::cout << "> Error loading temp image" << std::endl;exit(EXIT_FAILURE);
}cv::Mat output_image = cv::Mat::zeros(input_image.size(), CV_8UC3);// Compare values through matrices
for (int row = 0; row < input_image.rows; ++row)
{const uchar* ptr_input = input_image.ptr<uchar>(row);const uchar* ptr_compressed = compressed_image.ptr<uchar>(row);uchar* ptr_out = output_image.ptr<uchar>(row);for (int column = 0; column < input_image.cols; column++){// Calc abs diff for each color channel multiplying by a scale factorptr_out[0] = abs(ptr_input[0] - ptr_compressed[0]) * scale;ptr_out[1] = abs(ptr_input[1] - ptr_compressed[1]) * scale;ptr_out[2] = abs(ptr_input[2] - ptr_compressed[2]) * scale;ptr_input += 3;ptr_compressed += 3;ptr_out += 3;}
}// Shows processed image
cv::imshow("Error Level Analysis", output_image);
} int main (int argc, char* argv[])
{
// Verifica se o número de parâmetros necessário foi informado
if (argc < 2)
{std::cout << "> You need to provide an image as parameter" << std::endl;return EXIT_FAILURE;
}// Read the image
input_image = cv::imread(argv[1]);// Check image load
if (input_image.empty())
{std::cout << "> Error loading input image" << std::endl;return EXIT_FAILURE;
}// Set up window and trackbar
cv::namedWindow("Error Level Analysis", CV_WINDOW_AUTOSIZE);
cv::imshow("Error Level Analysis", input_image);
cv::createTrackbar("Scale", "Error Level Analysis", &scale, 100,   processImage);
cv::createTrackbar("Quality", "Error Level Analysis", &quality, 100, processImage);// Press 'q' to quit
while (char(cv::waitKey(0)) != 'q') {};return EXIT_SUCCESS;
} 

https://github.com/shreyneil/image_test/blob/master/ela.cpp

Contributions are welcome. Thank you.

Answer

It isn't really clear what you hope to accomplish by this, but it's pretty easy to make the functions callable from Cython. Start by making some small changes to main - it will need renaming so that it no longer acts as the main function for a program, and since you only use the second command-line argument as a file name you should change it to:

void some_function(char* filename) {// Read the imageinput_image = cv::imread(filename);// everything else the same
}

Then create your Cython wrapper cy_wrap.pyx. There are two parts to this. First you need to tell Cython about your two C++ functions (cdef extern from). Second you'll need to write a small wrapper function that can call these from Python:

cdef extern from "ela.hpp":# you'll need to create ela.hpp with declarations for your two functionsvoid processImage(int, void*)void some_function(char* filename)# and Python wrappers
def processImagePy():# since the parameters are ignored in C++ we can pass anythingprocessImage(0,NULL)def some_functionPy(filename):# automatic conversion from string to char*some_function(filename)

Using this module you'll be able to call processImagePy and some_functionPy.

To compile it to a Python module you'll need to write a setup.py file. I suggest you follow the template given in the Cython documentation (which you have read, right?). Your source files will be cy_wrap.pyx and ela.cpp. You'll probably want to link to the OpenCV library. You'll need to specify language="c++"

https://en.xdnf.cn/q/119439.html

Related Q&A

Setting yticks Location Matplotlib

Im trying to create a plot which has y axis exactly same with this : And Im in this situation and everything is ok until this point:When i try this lines:ax.set_yticks(range(20,67,10)) ax.set_yticklabe…

How to merge list to become string without adding any character in python?

I found that I can join them with -.join(name) but I dont want to add any character. Lets say I have [stanje1, |, st6, , stanje2, |, #] and I want to be like thisstanje1|st6,stanje2|#

Removing a key from a nested dictionary based on value

I previusly asked about adding, and someone helped me out with append. My new problem is trying to delete a key with a nested list, e.g.:JSON:data = {"result":[{"name":"Teddy&q…

Is dot product and normal multiplication results of 2 numpy arrays same?

I am working with kernel PCA in Python and I have to find the values after projecting the original data to the principal components.I use the equation fv = eigvecs[:,:ncomp]print(len(fv))td = fv.T …

Tkinter Entry widget stays empty in larger programs (Python 2)

I want to make a program where, after clicking on a button, a user gets asked for its name, after which the program continues. Im stuck on making the popup return the textstring that has been entered i…

How do i implement this python tree linked list code in dart?

Here is the python codedef tree(root_label, branches=[]):for branch in branches:assert is_tree(branch), branches must be treesreturn [root_label] + list(branches)def label(tree):return tree[0]def branc…

How can i find the ips in network in python

How can i find the TCP ips in network with the range(i.e 132.32.0.3 to 132.32.0.44) through python programming and also want to know the which ips are alive and which are dead. please send me.. thanks …

Python Coding (call function / return values)

I am having trouble writing code for this question. I have seen this question asked in a few places but I still cannot figure out the answer from the tips they provided. The question is: Write a progr…

discord.py Mention user by name

I am trying to mention a user by their name in discord.py. My current code is: @bot.command(name=mention) @commands.has_role(OwnerCommands) async def mention(ctx, *, member: discord.Member):memberid = …

Python unexpected EOF while parsing : syntax error

I am trying to do a simple toto history with a dictionary and function however I have this funny syntax error that keeps appearing that states "unexpected EOF while parsing" on the python she…