赞
踩
Hi,大家好,我是半亩花海。 本实验旨在利用 Python 和 OpenCV 库,通过图像处理和边缘检测算法实现黄豆图像的自动识别和计数,并在图像上标记每个黄豆的轮廓和序号。
import cv2
import matplotlib.pyplot as plt
# 读取图像
image = cv2.imread('soybean.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 平滑处理
blurred = cv2.GaussianBlur(gray, (11, 11), 0)
soybean.jpg 图片如下所示,可自取:
# 使用Canny边缘检测
edges = cv2.Canny(blurred, 30, 150)
# 查找轮廓
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓并标记序号
for i, contour in enumerate(contours):
# 计算轮廓的边界框,用于确定标注位置
x, y, w, h = cv2.boundingRect(contour)
# 绘制轮廓
cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)
# 在轮廓内标注序号
cv2.putText(image, str(i + 1), (x + w // 2, y + h // 2), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# 显示结果图像
plt.figure(figsize=(10, 10))
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()
# 输出黄豆数量
print(f"黄豆数量: {len(contours)}")
实验结果表明:图像中的所有18个黄豆都被成功识别和标记,每个黄豆的轮廓被绿色线条清晰绘制,序号标记在轮廓中心位置附近。
import cv2 import matplotlib.pyplot as plt # 读取图像 image = cv2.imread('soybean.jpg') # 转换为灰度图像 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 平滑处理 blurred = cv2.GaussianBlur(gray, (11, 11), 0) # 使用Canny边缘检测 edges = cv2.Canny(blurred, 30, 150) # 查找轮廓 contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 绘制轮廓并标记序号 for i, contour in enumerate(contours): # 计算轮廓的边界框,用于确定标注位置 x, y, w, h = cv2.boundingRect(contour) # 绘制轮廓 cv2.drawContours(image, [contour], -1, (0, 255, 0), 2) # 在轮廓内标注序号 cv2.putText(image, str(i + 1), (x + w // 2, y + h // 2), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2) # 显示结果图像 plt.figure(figsize=(10, 10)) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() # 输出黄豆数量 print(f"黄豆数量: {len(contours)}")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。