from maix import image, camera, display, app, time
import numpy as np
import cv2
# 硬件初始化
cam = camera.Camera(320, 240)
disp = display.Display()
# 智能参数配置
params = {
'preprocess': {
'blur_kernel': 5, # 中值滤波核大小 [3/5/7]
'gauss_kernel': (3,3), # 高斯模糊核
'cliplimit': 1.6 # CLAHE对比度限制
},
'edge': {
'canny_th1': 45, # 动态计算阈值基数
'canny_ratio': 2.5, # 高低阈值比例
'morph_kernel': (3,3) # 边缘连接核
},
'contour': {
'min_area': 200, # 动态最小面积
'solidity_thresh': 0.98, # 轮廓密实度阈值
'wh_ratio_range': (0.3, 5.0) # 宽高比范围
}
}
while not app.need_exit():
# 1. 图像采集与预处理
img = cam.read()
img_raw = image.image2cv(img, copy=False)
gray = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY)
# # 2. 智能光照补偿
# clahe = cv2.createCLAHE(
# clipLimit=params['preprocess']['cliplimit'],
# tileGridSize=(8,8))
# normalized = clahe.apply(gray)
# 3. 自适应降噪
blurred = cv2.bilateralFilter( gray, d=6, sigmaColor=50, sigmaSpace=50)
# 4. 动态边缘检测
median = np.median(blurred)
sigma = 0.1
lower = int(max(0, (1.0 - sigma) * median))
upper = int(min(255, (1.0 + sigma) * median * params['edge']['canny_ratio']))
edged = cv2.Canny(blurred, lower, upper)
# 5. 边缘连接优化
kernel = cv2.getStructuringElement(
cv2.MORPH_ELLIPSE,
params['edge']['morph_kernel'])
connected = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)
# 6. 多维度轮廓过滤
contours, hierarchy = cv2.findContours(
connected,
cv2.RETR_CCOMP,
cv2.CHAIN_APPROX_TC89_L1
)
valid_contours = []
for i, cnt in enumerate(contours):
# 基础过滤
area = cv2.contourArea(cnt)
if area < params['contour']['min_area']:
continue
# 几何特征分析
hull = cv2.convexHull(cnt)
solidity = area / cv2.contourArea(hull)
x,y,w,h = cv2.boundingRect(cnt)
aspect_ratio = w / float(h)
epsilon = 0.015 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
# 高级过滤条件
if (solidity < params['contour']['solidity_thresh'] or
not params['contour']['wh_ratio_range'][0] < aspect_ratio < params['contour']['wh_ratio_range'][1] or
len(approx) != 4): # 四角近似轮廓
continue
valid_contours.append(cnt)
# 层级感知绘制
color = (0,255,0) if hierarchy[0][i][3] == -1 else (0,0,255)
cv2.drawContours(img_raw, [cnt], -1, color, 1)
# 角点标注
for pt in approx:
cv2.circle(img_raw, tuple(pt[0]), 4, (255,255,0), -1)
# 计算矩形中心点
M = cv2.moments(cnt)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# 绘制红色实心点标记中心点
cv2.circle(img_raw, (cX, cY), 5, (0, 0, 255), -1)
# 打印中心点坐标
# print(f"矩形中心点坐标: ({cX}, {cY})")
disp.show(image.cv2image(img_raw))优化识别精度,和帧率
最新发布