处理绿色区域¶
通过上次的结果
提取出绿色区域,使用findContours和rectangle函数用最小外接矩形框出绿色区域,并获取坐标
contour_image = image.copy()
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(contour_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
由于绿色区域的字符太小,需要将绿色区域放大处理,使其占更多的像素
if contours:
c = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(c)
# 裁剪绿色区域
cropped_green = image[y:y + h, x:x + w]
# 放大裁剪后的区域(这里放大2倍作为示例)
resized_green = cv2.resize(cropped_green, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
框出黑色字符¶
对放大后的绿色区域进行预处理
# 在放大的绿色区域内查找黑色字符
gray_resized = cv2.cvtColor(resized_green, cv2.COLOR_BGR2GRAY)
_, binary_resized = cv2.threshold(gray_resized, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 可选:形态学操作来清理图像
kernel = np.ones((3, 3), np.uint8)
cleaned = cv2.morphologyEx(binary_resized, cv2.MORPH_OPEN, kernel)
# 查找并绘制字符轮廓
contours_chars, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours_chars:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(resized_green, (x, y), (x + w, y + h), (0, 0, 255), 2) # 在放大的绿色区域上绘制轮廓
# 显示放大的绿色区域
cv2.imshow('Detected Characters in Enlarged Green Region', resized_green)
识别结果¶
上传gitee¶
前往gitee查看
上传成功