def find_center(img): h, w = img.shape roi_h = int(h * 2 / 3) roi_img = img[roi_h:, :] img_blur = cv2.GaussianBlur(roi_img, (15, 15), 0) # 高斯模糊 ret, th2 = cv2.threshold(img_blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) g2 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) open_img = cv2.morphologyEx(th2, cv2.MORPH_OPEN, g2, iterations=3) x_sum = np.sum(open_img, axis=0) x_point = np.where(x_sum > 0) point_x = int((x_point[0][0] + x_point[0][-1]) / 2) # print(roi_h, w) # np.savetxt('reshape_data.txt', x_point, delimiter=' ', fmt='%i') return point_x c++ Eigen opencv
时间: 2023-12-03 12:04:22 浏览: 71
这段代码是一个Python函数,用于从一张图像中找到中心点的x坐标。其中使用了OpenCV库中的一些函数进行图像处理。
如果需要将这段代码转化为C++代码,可以使用Eigen和OpenCV库来实现:
```c++
#include <opencv2/opencv.hpp>
#include <Eigen/Core>
int find_center(cv::Mat img) {
int h = img.rows;
int w = img.cols;
int roi_h = h * 2 / 3;
cv::Mat roi_img = img(cv::Rect(0, roi_h, w, h - roi_h));
cv::Mat img_blur;
cv::GaussianBlur(roi_img, img_blur, cv::Size(15, 15), 0);
cv::Mat th2;
cv::threshold(img_blur, th2, 0, 255, cv::THRESH_BINARY + cv::THRESH_OTSU);
cv::Mat g2 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
cv::Mat open_img;
cv::morphologyEx(th2, open_img, cv::MORPH_OPEN, g2, cv::Point(-1, -1), 3);
Eigen::MatrixXi open_mat(h - roi_h, w);
for (int i = 0; i < h - roi_h; i++) {
for (int j = 0; j < w; j++) {
open_mat(i, j) = open_img.at<uchar>(i, j);
}
}
Eigen::VectorXi x_sum(w);
for (int i = 0; i < w; i++) {
x_sum(i) = open_mat.col(i).sum();
}
Eigen::ArrayXi x_point = (x_sum.array() > 0).select(Eigen::ArrayXi::LinSpaced(w, 0, w - 1), -1);
int point_x = (x_point(0) + x_point(w - 1)) / 2;
return point_x;
}
```
注意,此处使用了Eigen库来进行矩阵计算,需要在代码中引入相应的头文件和命名空间。同时,将OpenCV中的Mat转换为Eigen库中的Matrix类型,需要使用循环将每个像素的值拷贝到矩阵中。
阅读全文