User Tools

Site Tools


guides:opencv

This is an old revision of the document!


Instructions for integrating OpenCV with Folk.

1. Install OpenCV

 sudo apt-get install -y libopencv-dev

2. Create a C wrapper for the OpenCV functions you want to use

OpenCVWrapper.h

#ifndef OPENCV_WRAPPER_H
#define OPENCV_WRAPPER_H
 
#ifdef __cplusplus
extern "C" {
#endif
 
typedef struct {
    uint32_t width;
    uint32_t height;
    int components;
    uint32_t bytesPerRow;
    uint8_t *data;
} cv_image_t;
 
int getWidthOfImage(cv_image_t img);
 
cv_image_t myAdaptiveThreshold(cv_image_t img);
 
#ifdef __cplusplus
}
#endif
 
#endif // OPENCV_WRAPPER_H

OpenCVWrapper.cpp

#include <opencv2/opencv.hpp>
#include <iostream>
 
extern "C" {
    #include "OpenCVWrapper.h"
 
    int getWidthOfImage(cv_image_t img) {
        return img.width;
    }
 
    cv::Mat convertToMat(const cv_image_t& img) {
        int type = 0;
 
        // Determine the correct type based on number of components
        if (img.components == 1) {
            type = CV_8UC1; // Grayscale
        } else if (img.components == 3) {
            type = CV_8UC3; // RGB
        } else {
            // Add more cases if needed
            throw std::runtime_error("Unsupported number of components");
        }
 
        // Create cv::Mat with the given size, type, and data
        // Note: The step is the number of bytes per row
        return cv::Mat(img.height, img.width, type, img.data, img.bytesPerRow);
    }
 
    cv_image_t convertToImageT(const cv::Mat& mat) {
        cv_image_t img;
 
        img.width = static_cast<uint32_t>(mat.cols);
        img.height = static_cast<uint32_t>(mat.rows);
        int type = mat.type();
        if (type == CV_8UC1) {
            img.components = 1;
        } else if (type == CV_8UC3) {
            img.components = 3;
        }
        img.bytesPerRow = static_cast<uint32_t>(mat.step); // or mat.step1()
 
        // Allocate memory for the data
        size_t dataSize = mat.step * mat.rows; // or mat.total() * mat.elemSize()
        img.data = new uint8_t[dataSize];
 
        // Copy the data from the cv::Mat
        std::memcpy(img.data, mat.data, dataSize);
 
        return img;
    }
 
    cv_image_t myAdaptiveThreshold(cv_image_t img) {
        cv::Mat inputImage = convertToMat(img);
        cv::Mat outputImage;
        adaptiveThreshold(inputImage, outputImage, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 11, 2);
        return convertToImageT(outputImage);
    }
}
guides/opencv.1706580716.txt.gz · Last modified: 2024/01/30 02:11 by discord

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki