C# WPF调用C++ dll 结合opencv

news/2025/2/22 5:47:21

第一步、打开vs2019(其他版本的也可以),创建新项目

第二步、选择c++,并创建dll 项目

 

 第三步、在vs2019新项目中配置opencv

 

第四步、配置完成后写代码(写在dllmain.cpp中)

#include "pch.h"
#include <opencv2/opencv.hpp>
#include <iostream>

// 定义导出函数
extern "C" __declspec(dllexport) bool ConvertToGrayscale(const char* inputPath, const char* outputPath) {
    try {
        // 读取输入图像
        cv::Mat image = cv::imread(inputPath);
        if (image.empty()) {
            std::cerr << "Could not open or find the image" << std::endl;
            return false;
        }

        // 将图像转换为灰度图像
        cv::Mat grayImage;
        cv::cvtColor(image, grayImage, cv::COLOR_BGR2GRAY);

        // 保存灰度图像
        bool saved = cv::imwrite(outputPath, grayImage);
        if (!saved) {
            std::cerr << "Could not save the grayscale image" << std::endl;
            return false;
        }

        return true;
    }
    catch (const cv::Exception& e) {
        std::cerr << "OpenCV exception: " << e.what() << std::endl;
        return false;
    }
}

第五步、生成完成后在debug中有dll文件拷贝到WPF的根目录下,如果拷贝到根目录下还没成功的话写好具体地址。

 WPF代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.IO;

namespace WpfAppopencvsharp
{
    public partial class MainWindow : Window
    {
        // 导入DLL中的函数D:\\codeproject\\WpfAppopencvsharp\\WpfAppopencvsharp\\bin\\Debug\\dll\\x64\\
        [DllImport("D:\\codeproject\\WpfAppopencvsharp\\WpfAppopencvsharp\\bin\\Debug\\dll\\x64\\TestDll.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern bool ConvertToGrayscale(string inputPath, string outputPath);
        public MainWindow()
        {
            InitializeComponent();

        }

        private void ChangeImage(object sender, RoutedEventArgs e)
        {
            // 加载图片资源(确保路径正确)
            var imagePath = "C:\\Users\\1\\Desktop\\11.jpg"; // 如果图片在Resources文件夹中,使用这种方法加载。如果不是,使用相对路径或绝对路径。
            imageControl.Source = new BitmapImage(new Uri(imagePath, UriKind.Absolute));


        }

        private void GrayImage(object sender, RoutedEventArgs e)
        {
            // 输入和输出图像的路径
            string inputPath = "C:\\Users\\1\\Desktop\\11.jpg";
            string outputPath = "D:\\codeproject\\WpfAppopencvsharp\\output.jpg";

            // 调用DLL函数
            bool success = ConvertToGrayscale(inputPath, outputPath);
            if (success)
            {
                MessageBox.Show("图像转换成功!");
                // 显示灰度图像
                if (File.Exists(outputPath))
                {
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri(outputPath, UriKind.RelativeOrAbsolute);
                    bitmap.EndInit();
                    // 假设XAML中有一个名为image的Image控件
                    imageControl.Source = bitmap;
                }
            }
            else
            {
                MessageBox.Show("图像转换失败!");
            }
        }
    }
}

第六步、运行一下

以上是具体步骤,有opencv和wpf基础的可参考以下: 

1. 创建 C++ DLL 项目

步骤:
  1. 打开 Visual Studio,创建一个新的 “动态链接库 (DLL)” 项目。
  2. 确保已安装 OpenCV 库,并配置项目的包含目录、库目录和链接器输入。
代码实现:
#include <opencv2/opencv.hpp>
#include <iostream>

// 定义导出函数
extern "C" __declspec(dllexport) bool ConvertToGrayscale(const char* inputPath, const char* outputPath) {
    try {
        // 读取输入图像
        cv::Mat image = cv::imread(inputPath);
        if (image.empty()) {
            std::cerr << "Could not open or find the image" << std::endl;
            return false;
        }

        // 将图像转换为灰度图像
        cv::Mat grayImage;
        cv::cvtColor(image, grayImage, cv::COLOR_BGR2GRAY);

        // 保存灰度图像
        bool saved = cv::imwrite(outputPath, grayImage);
        if (!saved) {
            std::cerr << "Could not save the grayscale image" << std::endl;
            return false;
        }

        return true;
    }
    catch (const cv::Exception& e) {
        std::cerr << "OpenCV exception: " << e.what() << std::endl;
        return false;
    }
}
代码解释:
  • ConvertToGrayscale 函数接受两个参数:输入图像的路径和输出灰度图像的路径。
  • 使用 cv::imread 读取输入图像。
  • 使用 cv::cvtColor 将图像转换为灰度图像。
  • 使用 cv::imwrite 保存灰度图像。

2. 编译 DLL

编译项目,生成 DLL 文件。确保将 OpenCV 的动态链接库(.dll 文件)复制到生成的 DLL 文件所在的目录。

3. 创建 C# WPF 应用程序

步骤:
  1. 打开 Visual Studio,创建一个新的 “WPF 应用程序” 项目。
代码实现:
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media.Imaging;
using System.IO;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        // 导入DLL函数
        [DllImport("YourDllName.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern bool ConvertToGrayscale(string inputPath, string outputPath);

        public MainWindow()
        {
            InitializeComponent();

            // 输入和输出图像的路径
            string inputPath = "input.jpg";
            string outputPath = "output.jpg";

            // 调用DLL函数
            bool success = ConvertToGrayscale(inputPath, outputPath);
            if (success)
            {
                MessageBox.Show("图像转换成功!");
                // 显示灰度图像
                if (File.Exists(outputPath))
                {
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri(outputPath, UriKind.RelativeOrAbsolute);
                    bitmap.EndInit();
                    // 假设XAML中有一个名为image的Image控件
                    image.Source = bitmap;
                }
            }
            else
            {
                MessageBox.Show("图像转换失败!");
            }
        }
    }
}
XAML 代码:
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Image x:Name="image" HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="300"/>
    </Grid>
</Window>
代码解释:
  • 使用 [DllImport] 特性导入 C++ DLL 中的 ConvertToGrayscale 函数。
  • 在 MainWindow 构造函数中调用该函数,将输入图像转换为灰度图像。
  • 如果转换成功,显示成功消息并在 Image 控件中显示灰度图像。

4. 注意事项

  • 确保 C# 项目中引用的 DLL 文件名与 C++ 项目生成的 DLL 文件名一致。
  • 确保输入图像文件存在于指定的路径。
  • 确保将 OpenCV 的动态链接库复制到 C# 应用程序的可执行文件所在的目录。

通过以上步骤,你可以将图像转换为灰度图像的功能封装成 DLL,并在 C# WPF 应用程序中调用该 DLL。


http://www.niftyadmin.cn/n/5861680.html

相关文章

蓝桥杯 r格式(高精度*低精度)

输入样例&#xff1a;2 3.14 输出样例&#xff1a;13 思路&#xff1a;首先注意到本题的数字大小很大&#xff0c;需要用到高精度&#xff0c;因此应该定义string来存储数据d&#xff0c;为了后续计算&#xff0c;在存储完字符串d之后还需要先将每一位转化为数字并且找到小数点…

Flutter项目中设置安卓启动页

AndroidManifest.xml 设置 android:theme“style/LaunchTheme” <applicationandroid:label"string/app_name"android:name"${applicationName}"android:icon"mipmap/ic_launcher"android:roundIcon"mipmap/ic_launcher"android:t…

阿里云通过docker安装skywalking及elasticsearch操作流程

系统 本文使用系统为 Alibaba Cloud Linux 3.2104 LTS 64位 配置为 4核8G PS&#xff1a;最低配置应为2核4G&#xff0c;配置过低无法启动 安装docker 1.卸载旧版本docker yum remove docker \docker-client \docker-client-latest \docker-common \docker-latest \docker-…

零基础学QT、C++(五)QT编译、导入OpenCV

目录 一、前言 二、准备工作 三、下载OpenCV包 四、包目录 五、版本匹配问题 六、QT导入OpenCV 七、手动编译OpenCV 1、导入项目&#xff08;他会加载很久&#xff0c;耐心等待&#xff09; 2、项目导入完成后&#xff0c;我们就可以开始构建 3、构建完成&#xff0c;就可以看看…

DuodooBMS源码解读之 equipment_work_order模块

Odoo 18 MrpWorkOrder 扩展模块用户使用手册 一、引言 本用户使用手册旨在帮助你了解并使用基于 Odoo 18 原生模块扩展的 MrpWorkOrder 模块。该扩展模块为制造工单管理提供了额外的功能&#xff0c;包括设备作业单关联、生产数量计算、检验合格数量统计等。通过本手册&#…

UI 自动化测试框架介绍

UI 自动化测试框架是用于模拟用户操作、验证界面功能和行为的工具。以下是一些常见的 UI 自动化测试框架,适用于不同的平台和技术栈: 1. Web UI 自动化框架 用于测试 Web 应用程序的 UI 自动化框架: Selenium: Java、Python、C#、JavaScript、Ruby 等。 : 支持多种浏览器(…

11、k8s的hpa和rancher

hpa hpa概念 hpa&#xff1a;自动对pod的数量进行扩缩容。 修改pod的数量&#xff1a; 1、手动——基于控制器——deployment statefulset(副本数) 2、自动扩缩容——基于资源限制的字段&#xff0c;达到阈值之后可以对pod的数量进行自动增加&#xff0c;小于阈值时可以自…

百度搜索,能否将DeepSeek变成“内功”?

最近&#xff0c;所有的云平台和主流APP都在努力接入DeepSeek。其中&#xff0c;搜索类APP与搜索引擎更是“战况激烈”。那么问题来了&#xff0c;接入DeepSeek已经变成了标准配置&#xff0c;到底应该如何做出差异化&#xff1f;接入DeepSeek这件事能不能实现11大于2的效果&am…