下面是一个用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助手提供,问题来源于学员提问