将以下的python程序转化为c++版本,并在vs2022上实现。import cv2 import numpy as np from skimage.transform import radon import os thre1=10 thre2=-10 r=60 maxVal = 0 index = 0 sequence_path = "./images/" for file in os.listdir(sequence_path): filename=os.path.join(sequence_path, file) image=cv2.imread(filename, 0) image=cv2.blur(image,(3,3)) img=np.zeros((len(image), len(image[0])),np.uint8) maxVal = 0 index = 0 retval, labels, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8) for i in range(1, len(stats)): if stats[i][4] > maxVal: maxVal = stats[i][4] index = i #x,y,h,w s for i in range(len(labels)): for j in range(len(labels[0])): if labels[i][j]==index: labels[i][j]=255 else: labels[i][j] = 0 cv2.imwrite('./4-max_region.jpg',labels) img2=cv2.imread('./4-max_region.jpg',0) img3=cv2.Canny(img2,15,200) # theta = np.linspace(0, 180, endpoint=False) img4 = radon(img3) max_angel=0 for i in range(len(img4)): for j in range(len(img4[0])): if img4[i][j]>max_angel: max_angel=img4[i][j] angel=j print("{}方向为:{} °".format(filename,angel))
时间: 2024-04-10 19:34:13 浏览: 97
在VS2022上实现这段Python代码的C++版本,你可以使用以下代码作为参考:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <opencv2/imgcodecs.hpp>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
using namespace cv;
int main() {
int thre1 = 10;
int thre2 = -10;
int r = 60;
int maxVal = 0;
int index = 0;
string sequence_path = "./images/";
for (const auto &entry : filesystem::directory_iterator(sequence_path)) {
string filename = entry.path().string();
Mat image = imread(filename, IMREAD_GRAYSCALE);
blur(image, image, Size(3,3));
Mat img(image.rows, image.cols, CV_8U, Scalar(0));
maxVal = 0;
index = 0;
Mat labels, stats, centroids;
int retval = connectedComponentsWithStats(img, labels, stats, centroids, 8);
for (int i = 1; i < stats.rows; i++) {
if (stats.at<int>(i, CC_STAT_AREA) > maxVal) {
maxVal = stats.at<int>(i, CC_STAT_AREA);
index = i;
}
}
for (int i = 0; i < labels.rows; i++) {
for (int j = 0; j < labels.cols; j++) {
if (labels.at<int>(i, j) == index)
labels.at<int>(i, j) = 255;
else
labels.at<int>(i, j) = 0;
}
}
imwrite("./4-max_region.jpg", labels);
Mat img2 = imread("./4-max_region.jpg", IMREAD_GRAYSCALE);
Mat img3;
Canny(img2, img3, 15, 200);
Mat img4;
radon(img3, img4);
int max_angel = 0;
int angel = 0;
for (int i = 0; i < img4.rows; i++) {
for (int j = 0; j < img4.cols; j++) {
if (img4.at<float>(i, j) > max_angel) {
max_angel = img4.at<float>(i, j);
angel = j;
}
}
}
cout << filename << " 方向为:" << angel << " °" << endl;
}
return 0;
}
```
请注意,你需要在项目中添加OpenCV库的链接。此外,代码中使用了C++17的filesystem库进行文件遍历,因此你需要在编译时启用C++17标准。
阅读全文