ZBLOG

C++ 实现图像水平 n等分

下面是一个用C++实现图像水平n等分的示例代码:

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

using namespace std;
using namespace cv;

// 图像水平n等分函数
Mat splitImageHorizontally(Mat image, int n) {
    int rows = image.rows;
    int cols = image.cols;
    
    if (cols % n != 0) {
        cerr << "Error: Image cannot be evenly split horizontally." << endl;
        return image;
    }
    
    int subWidth = cols / n;  // 子图像宽度
    
    Mat resultImage(rows, cols, CV_8UC3);
    
    for (int i = 0; i < n; ++i) {
        Rect roi(i * subWidth, 0, subWidth, rows);  // 每个子图像的感兴趣区域
        Mat subImage = image(roi);                  // 提取子图像
        Mat dstROI(resultImage, roi);               
        
        subImage.copyTo(dstROI);                     // 将子图像复制到结果图像中
    }
    
    return resultImage;
}

int main() {
    string imagePath = "image.jpg"; // 图像路径
    
    Mat originalImage = imread(imagePath);   // 加载原始图像

    if (originalImage.empty()) {
        cerr << "Error: Failed to load the image." << endl;
        return -1;
    }
    
    int n = 4;   // 分割数目,这里示例分成4份
    
    Mat dividedImage = splitImageHorizontally(originalImage, n);
    
    namedWindow("Original Image", WINDOW_NORMAL);
    namedWindow("Divided Image", WINDOW_NORMAL);
    
    imshow("Original Image", originalImage);
    imshow("Divided Image", dividedImage);
    
    waitKey(0);
    
    return 0;
}

这段代码使用了OpenCV库来处理图像,首先通过imread函数加载原始图像,然后调用splitImageHorizontally函数将图像水平等分成n份。最后展示原始图像和分割后的图像。

请确保安装了OpenCV库,并将示例代码中的image.jpg替换为你自己的图像路径。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=7839

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?