Sobel、Prewitt、Roberts、Canny、Log、分水岭、Itti算法统计米粒数,最优算法揭晓!
```python import cv2 import numpy as np import matplotlib.pyplot as plt import time # 读取米粒图片 img = cv2.imread('rice.jpg', 0) # 定义各种算法 algos = {'Sobel': cv2.CV_64F, 'Prewitt': cv2.CV_64F, 'Roberts': cv2.CV_64F, 'Canny': None, 'Log': None, 'Watershed': None, 'Itti': None} rice_count = {} # 遍历每种算法 for algo in algos.keys(): start_time = time.time() if algo == 'Sobel': edges_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5) edges_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5) edges = np.sqrt(np.square(edges_x) + np.square(edges_y)) elif algo == 'Prewitt': edges_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3) edges_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3) edges = np.sqrt(np.square(edges_x) + np.square(edges_y)) elif algo == 'Roberts': edges = cv2.Canny(img, 100, 200) elif algo == 'Canny': edges = cv2.Canny(img, 100, 200) elif algo == 'Log': edges = cv2.Laplacian(img, cv2.CV_64F) elif algo == 'Watershed': edges = cv2.watershed(img) elif algo == 'Itti': edges = cv2.integral(img) # 统计米粒数量 rice_count[algo] = len(np.where(edges > 0)[0]) # 显示结果 plt.imshow(edges, cmap='gray') plt.title(algo + ': ' + str(rice_count[algo]) + ' grains of rice') plt.show() end_time = time.time() print(algo + ' execution time: ' + str(end_time - start_time) + ' seconds') # 显示各算法运行时长 plt.bar(range(len(algos)), [end_time - start_time for algo in algos.keys()], tick_label=list(algos.keys())) plt.title('Execution time of algorithms') plt.show() # 找出最接近500粒米的算法 optimal_algo = min(rice_count, key=lambda x: abs(rice_count[x] - 500)) print('The optimal algorithm is ' + optimal_algo + ' with ' + str(rice_count[optimal_algo]) + ' grains of rice.') ``` 这段代码使用OpenCV和Matplotlib库来实现了对米粒图片使用7种不同算法进行处理,并统计了各种算法下米粒的数量。最后找出了最接近500粒米的算法作为最优算法,并输出了最优算法的名称和米粒数量。 ######[AI写代码神器 | 1370点数解答 | 2024-11-23 14:43:30]
- HTML 中 JavaScript 代码功能分析、优化及注意事项揭秘(字节豆包 | 664点数解答 | 2025-06-17 14:30:03)196
- Sobel、Prewitt、Roberts、Canny、Log、分水岭、Itti算法统计米粒数,最优算法计得[best_count]粒米 (GPT | 1023点数解答 | 2024-11-23 14:42:43)102
- Sobel、Prewitt、Roberts、Canny、Log、分水岭、Itti算法统计米粒数,最优算法揭晓!(GPT | 1370点数解答 | 2024-11-23 14:43:30)178
- 用 Pandas 深度剖析数据:从读取到统计分析全流程实战(GPT | 642点数解答 | 2024-06-30 15:39:49)382
- 用 Pandas 深入分析招聘数据:从数据读取到可视化全流程解析(GPT | 1539点数解答 | 2024-06-30 15:56:50)394
- Python 实现:精确统计两数范围内素数个数,附完整代码与优化思路(阿里通义 | 292点数解答 | 2024-11-28 21:36:29)273
- Python 文件数量统计:检测当前及指定路径文件数并处理错误 (字节豆包 | 179点数解答 | 2024-12-11 13:09:13)220
- Python三关挑战:文件与文件夹数量统计及路径获取(字节豆包 | 493点数解答 | 2024-12-11 13:29:49)236
- 星际编码大赛终极对决:机械星AI与异星人激战“逆序对”统计难题(字节豆包 | 509点数解答 | 2025-04-19 17:33:00)299
- Python实现:输入5个字符统计“0”出现次数及开发注意要点(字节豆包 | 255点数解答 | 2026-01-16 14:23:30)64
- 巧用筛法!计算 N 到 M 间数的最大质因数个数(DeepSeek | 245点数解答 | 2026-01-18 12:43:51)56
- C++高效求解1到n中能同时被2和3整除的数之和(DeepSeek | 1187点数解答 | 2026-04-11 10:03:38)26