以下是使用OpenCV库进行图像处理的C++代码,实现去除图像黑边的功能:
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
// 读取图像
Mat image = imread("input.jpg", IMREAD_COLOR);
if (image.empty()) {
printf("Could not open or find the image.\n");
return -1;
}
// 转换为灰度图像
Mat grayImage;
cvtColor(image, grayImage, COLOR_BGR2GRAY);
// 使用自适应阈值二值化处理
Mat thresholded;
adaptiveThreshold(grayImage, thresholded, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV, 11, 2);
// 查找轮廓
std::vector<std::vector<Point>> contours;
findContours(thresholded.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 找到最大轮廓
int maxContourIndex = -1;
double maxContourArea = 0.0;
for (int i = 0; i < contours.size(); ++i) {
double area = contourArea(contours[i]);
if (area > maxContourArea) {
maxContourArea = area;
maxContourIndex = i;
}
}
// 获取最大轮廓的边界框并裁剪图像
Rect boundingRect = boundingRect(contours[maxContourIndex]);
Mat croppedImage = image(boundingRect).clone();
// 显示结果并保存图像
imshow("Original Image", image);
imshow("Cropped Image", croppedImage);
imwrite("output.jpg", croppedImage);
waitKey(0);
return 0;
}
请将代码中的input.jpg
替换为你要处理的图像路径,代码将会读取该图像并输出去除黑边后的图像为output.jpg
。注意,在编译和运行之前,请确保已正确安装并配置了OpenCV库。
内容由零声教学AI助手提供,问题来源于学员提问