以下是一个使用OpenCV进行去黑边的示例代码(C++):
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 读取图像
Mat image = imread("input.jpg", IMREAD_COLOR);
// 检查图像是否成功加载
if (image.empty())
{
std::cout << "无法加载图像" << std::endl;
return -1;
}
// 创建输出图像,尺寸与输入图像相同
Mat result = Mat::zeros(image.size(), image.type());
// 计算黑边大小
int top = 0, bottom = 0, left = 0, right = 0;
// 获取非零像素边界
Rect roi = boundingRect(image);
// 计算黑边尺寸
top = roi.y;
bottom = image.rows - roi.y - roi.height;
left = roi.x;
right = image.cols - roi.x - roi.width;
// 添加黑边
copyMakeBorder(image, result, top, bottom, left, right, BORDER_CONSTANT);
// 显示原始图像和去黑边后的图像
imshow("Original Image", image);
imshow("Result", result);
waitKey(0);
return 0;
}
请注意,此代码假定输入图像名为”input.jpg”。您需要根据实际情况修改文件路径或名称,并确保已正确安装并链接了OpenCV库。
内容由零声教学AI助手提供,问题来源于学员提问




