将Python代码转换为C++代码可能需要一些适应性和语法调整。以下是给出的Python代码的C++版本:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
Mat original_img1 = imread("F:\\Image_2024_0528_1446_34_945-000030.bmp");
Mat roi_img1 = original_img1(Range(3001, 10235), Range(408, 7485));
imwrite("F:\\30.bmp", roi_img1);
Mat original_img2 = imread("F:\\Image_2024_0528_1446_37_867-000031.bmp");
Mat roi_img2 = original_img2(Range(1632, 8920), Range(411, 7485));
imwrite("F:\\31.bmp", roi_img2);
// Canny边缘检测
Mat img1;
GaussianBlur(original_img1, img1, Size(3, 3), 0);
Mat canny;
Canny(img1, canny, 50, 150);
// 形态学梯度运算
Mat thr_img;
threshold(original_img1, thr_img, 210, 255, THRESH_BINARY);
Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5));
Mat gradient;
morphologyEx(thr_img, gradient, MORPH_GRADIENT , kernel);
//imwrite("F:\\gradient.bmp", gradient);
//imwrite("F:\\canny.bmp", canny);
int height = canny.rows;
int width = canny.cols;
int threshold_val = 300;
int count_threshold_val = 20;
int top_boundary = -1;
int bottom_boundary = -1;
for (int row = 0; row < height; row++) {
int white_pixels_count = countNonZero(canny.row(row));
if (row != 0) {
int white_pixels_count_1 = countNonZero(canny.row(row - 1));
}
if (row != height - 1) {
int white_pixels_count_2 = countNonZero(canny.row(row + 1));
}
if (white_pixels_count > threshold_val || white_pixels_count_1 > threshold_val || white_pixels_count_2 > threshold_val) {
if (top_boundary == -1) {
top_boundary = row;
}
bottom_boundary = row;
}
}
std::cout << "上边界行数:" << top_boundary << std::endl;
std::cout << "下边界行数:" << bottom_boundary << std::endl;
return 0;
}
请确保安装并链接OpenCV库,并将图像文件的路径替换为您实际的文件路径。另外,请根据需要进行适当的调整和错误处理。
内容由零声教学AI助手提供,问题来源于学员提问




