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++ opencv Eigen::Tensor如何实现
时间: 2023-12-10 07:03:47 浏览: 46
首先需要在项目中引入Eigen库,然后可以通过以下代码实现:
```
#include <opencv2/opencv.hpp>
#include <unsupported/Eigen/CXX11/Tensor>
using namespace cv;
using namespace Eigen;
int find_center(Mat img) {
int h = img.rows;
int w = img.cols;
int roi_h = int(h * 2 / 3);
Mat roi_img = img(Rect(0, roi_h, w, h - roi_h));
Mat img_blur;
GaussianBlur(roi_img, img_blur, Size(15, 15), 0);
Mat th2;
threshold(img_blur, th2, 0, 255, THRESH_BINARY + THRESH_OTSU);
Mat g2 = getStructuringElement(MORPH_RECT, Size(3, 3));
Mat open_img;
morphologyEx(th2, open_img, MORPH_OPEN, g2, Point(-1, -1), 3);
Tensor<int, 1> x_sum(w);
for (int j = 0; j < w; j++) {
int sum = 0;
uchar* data = open_img.data + j;
for (int i = 0; i < open_img.rows; i++) {
sum += *data;
data += open_img.step;
}
x_sum(j) = sum;
}
std::vector<int> x_point;
for (int j = 0; j < x_sum.size(); j++) {
if (x_sum(j) > 0) {
x_point.push_back(j);
}
}
int point_x = (x_point.front() + x_point.back()) / 2;
return point_x;
}
```
这里使用了Eigen的Tensor来存储x_sum数组,避免了使用矩阵乘法的复杂度。同时,对于OpenCV中的二维数组,可以使用指针来进行遍历,避免了使用at()函数的性能损失。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)