写一个python实现珍珠图像形状圆形和椭圆形的判断的代码
时间: 2023-03-15 22:11:53 浏览: 149
import cv2
import numpy as np # 读取图像
img = cv2.imread('pearl.jpg') # 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 检测轮廓
contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # 绘制轮廓
for cnt in contours:
# 获取外接矩形
x, y, w, h = cv2.boundingRect(cnt)
# 计算矩形的长宽比
ratio = float(w) / h
# 如果是圆形,比例为1
if ratio > 0.95 and ratio < 1.05:
# 圆形
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
cv2.putText(img, 'Circle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
# 如果是椭圆,比例为2
elif ratio > 1.95 and ratio < 2.05:
# 椭圆
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
cv2.putText(img, 'Ellipse', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
# 显示图像
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
阅读全文