ZBLOG

转化为C_++ import matplotlib.pyplot as plt # 读取图像 image_path = r"F:AI/Learning/9022625033_K1609563_T001_4_13.jpg" image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # 使用Sobel算子进行边缘增强 sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3) sobely = c...

下面是将你提供的 Python 代码转换为 C++ 代码的示例,使用 OpenCV 库进行图像读取、边缘增强和显示。C++ 中没有 matplotlib,我们将用 OpenCV 的图形用户界面功能代替它。

  1. #include <opencv2/opencv.hpp>
  2. #include <iostream>
  3. using namespace cv;
  4. using namespace std;
  5. int main() {
  6. // 读取图像(以灰度模式)
  7. string image_path = "F:AI/Learning/9022625033_K1609563_T001_4_13.jpg";
  8. Mat image = imread(image_path, IMREAD_GRAYSCALE);
  9. if (image.empty()) {
  10. cerr << "Error: Could not open or find the image!" << endl;
  11. return -1;
  12. }
  13. // 使用Sobel算子进行边缘增强
  14. Mat sobelx, sobely, edge_enhanced_image;
  15. Sobel(image, sobelx, CV_64F, 1, 0, 3);
  16. Sobel(image, sobely, CV_64F, 0, 1, 3);
  17. // 将结果转换为8位无符号整型并计算边缘增强图像
  18. Mat magnitude;
  19. magnitude = abs(sobelx) + abs(sobely);
  20. edge_enhanced_image = image.clone();
  21. // 将幅度值归一化到[0-255]范围
  22. normalize(magnitude, magnitude, 0, 255, NORM_MINMAX);
  23. // 将幅度添加到原始图像中,确保结果在范围内
  24. edge_enhanced_image += magnitude;
  25. // 显示图像
  26. imshow("Original Image", image);
  27. imshow("Sobel X", sobelx);
  28. imshow("Sobel Y", sobely);
  29. imshow("Edge Enhanced Image", edge_enhanced_image);
  30. waitKey(0); // 等待按键
  31. return 0;
  32. }

注意事项:

  1. 包括头文件:需要包含 OpenCV 的主要头文件,并使用 cvstd 命名空间。

  2. 读取和检查图像:使用 imread() 函数以灰度模式读取图像,并检查是否成功加载。

  3. Sobel 算子

    • 使用 Sobel() 函数计算水平方向(sobelx)和垂直方向(sobely)的梯度。
    • 使用 abs() 确保幅值为正数,然后将其加在一起形成边缘增强效果。
  4. 显示结果:通过调用 imshow() 显示不同的窗口来展示原始图像、Sobel 边缘以及最终的边缘增强结果。

  5. 等待按键:最后,通过 waitKey(0) 暂停程序,直到用户按下任意键。这样可以让用户查看结果窗口。

编译与运行:

确保你的项目正确链接了 OpenCV 库。在 Windows 上,你可以使用 Visual Studio 或者其他 IDE 设置项目属性以链接相应的库文件。如果是在 Linux 下,可以通过命令行编译,如下所示:

  1. g++ your_code.cpp -o output_program `pkg-config --cflags --libs opencv4`

然后运行生成的可执行文件。记得调整路径和任何必要的参数。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=20917

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?