酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

采用sobel、prewitt、roberts、canny、log、分水岭、itti算法统计米粒图片中有多少粒米。算法输出是一个画布上排列7种算法结果,标题显示算法名称和米粒总数,第8幅图片显示各算法运行时长。选取最接近500粒米的算法作为最优算法。使用python语法

import cv2 import numpy as np import time from matplotlib import pyplot as plt # 读取米粒图片 img = cv2.imread('millets.jpg', 0) # 定义7种算法 algorithms = ['Sobel', 'Prewitt', 'Roberts', 'Canny', 'Log', 'Watershed', 'Itti'] counts = [] # 定义函数来统计米粒数量 def count_millets(img): # Sobel算法 sobel = cv2.Sobel(img, cv2.CV_64F, 1, 1, ksize=5) # Prewitt算法 prewitt = cv2.Canny(img, 100, 200) # Roberts算法 roberts = cv2.Robert(img, cv2.CV_64F) #Canny算法 canny = cv2.Canny(img, 100, 200) #Log算法 log = cv2.Laplacian(img, cv2.CV_64F, ksize=5) # 分水岭算法 _, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) # Itti算法 itti = cv2.ittisalience(img) return sobel, prewitt, roberts, canny, log, thresh, itti # 统计米粒数量 for i, algorithm in enumerate(algorithms): start_time = time.time() result = count_millets(img) end_time = time.time() counts.append(np.sum(result[i])) plt.subplot(3, 3, i+1) plt.imshow(result[i], cmap='gray') plt.title(algorithm + ' - ' + str(counts[i]) + ' grains') plt.show() # 绘制各算法运行时间 plt.imshow(end_time-start_time) plt.title('Execution Time for each algorithm') plt.show() # 找到粒数最接近500的算法 best_algo_index = np.argmin(np.abs(np.array(counts) - 500)) best_algo = algorithms[best_algo_index] best_count = counts[best_algo_index] print('The best algorithm for counting grains is:', best_algo) print('Total number of grains counted:', best_count) [2024-11-23 14:42:43 | AI写代码神器 | 1023点数解答]

相关提问