You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决OpenCV+C++开发中出现的整数除以零异常?

解决OpenCV整数除以零异常的方案

1. 修复图像读取失败后的程序流程

当imread失败返回空矩阵时,当前代码仅打印错误却继续执行后续的filter2D操作,这会导致处理空图像时触发内部的除以零异常。必须在判断图像为空后终止程序:

if (image.empty())
{
    cout << "Could not read image" << endl;
    return -1; // 终止程序,避免后续无效操作
}

2. 修正卷积核初始化错误

kernel1声明为5×5矩阵,但初始化时仅提供了9个元素,剩余元素会是未初始化的垃圾值,这会导致filter2D计算出现不可预料的错误。如果是要创建单位核(仅中心位置为1,其余为0),正确初始化代码如下:

// 5×5单位核,中心元素为1,其余为0
Mat kernel1 = (Mat_<double>(5, 5) << 
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 1, 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0);

若你原本想创建3×3的核,则需将声明改为(Mat_<double>(3, 3)),并提供9个元素。

3. 优化borderType参数可读性

filter2D最后一个参数4对应OpenCV的BORDER_REFLECT_101枚举值,建议直接使用枚举常量以提升代码可读性:

filter2D(image, identity, -1, kernel1, Point(-1, -1), 0, BORDER_REFLECT_101);

修正后的完整代码

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
    // 读取图像
    Mat image = imread("../Images/im092002.jpg");
    
    // 图像读取失败则打印错误并终止
    if (image.empty())
    {
        cout << "Could not read image" << endl;
        return -1;
    }
    // 应用单位滤波核
    Mat kernel1 = (Mat_<double>(5, 5) << 
        0, 0, 0, 0, 0,
        0, 0, 0, 0, 0,
        0, 0, 1, 0, 0,
        0, 0, 0, 0, 0,
        0, 0, 0, 0, 0);
    Mat identity;
    filter2D(image, identity, -1, kernel1, Point(-1, -1), 0, BORDER_REFLECT_101);
    imshow("Original", image);
    imshow("Identity", identity);

    // 应用均值模糊核
    Mat kernel2 = Mat::ones(5, 5,CV_64F);
    kernel2 = kernel2 / 25;
    Mat img;
    filter2D(image, img, -1, kernel2, Point(-1, -1), 0, BORDER_REFLECT_101);
    imshow("kernel blur", img);
    imwrite("blur_kernel.jpg", img);
    waitKey();
    destroyAllWindows();

    return 0;
}

注:已修正你第一个imshow中的标题拼写错误("Orginal"改为"Original")。

内容的提问来源于stack exchange,提问作者Peaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:01:08