You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python与OpenCV提取图片中两位数字间的区域?

用OpenCV + Python提取数字间区域的解决方案

嗨,我来帮你搞定这个提取数字间区域的需求!结合你给出的输入和期望输出,我整理了一套可行的步骤和代码,咱们一步步来:

整体思路

核心是先定位两个数字的位置,再根据它们的坐标划定要提取的区域:

  • 先对图片做预处理(灰度化、二值化),让数字和背景清晰区分开
  • 检测数字的轮廓,获取它们的边界框(bounding box)
  • 利用两个边界框的横向坐标,计算出整体区域,再拆分三个细分区域

完整代码实现

import cv2
import numpy as np

# 读取输入图片
img = cv2.imread('input_image.png')
# 复制原图用于后续结果保存
result_img = img.copy()

# 1. 图片预处理:灰度化 + 二值化(反转后数字为白色,背景为黑色,便于轮廓检测)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)

# 2. 检测轮廓并筛选数字轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 过滤掉小轮廓,只保留数字对应的轮廓(可根据实际图片调整面积阈值)
digit_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 500]
# 按x坐标排序,确保左边数字在前、右边数字在后
digit_contours.sort(key=lambda x: cv2.boundingRect(x)[0])

# 获取两个数字的边界框坐标
x1, y1, w1, h1 = cv2.boundingRect(digit_contours[0])
x2, y2, w2, h2 = cv2.boundingRect(digit_contours[1])

# 3. 计算并提取整体区域
# 整体区域的y范围取两个数字的上下边界,x范围从左数字右侧到右数字左侧
overall_y_min = min(y1, y2)
overall_y_max = max(y1 + h1, y2 + h2)
overall_x_min = x1 + w1
overall_x_max = x2
overall_region = img[overall_y_min:overall_y_max, overall_x_min:overall_x_max]

# 4. 拆分并提取三个细分区域
region_total_width = overall_x_max - overall_x_min
split_width = region_total_width // 3

# 区域1:整体区域的左三分之一
region1 = img[overall_y_min:overall_y_max, overall_x_min:overall_x_min + split_width]
# 区域2:整体区域的中间三分之一
region2 = img[overall_y_min:overall_y_max, overall_x_min + split_width:overall_x_min + 2*split_width]
# 区域3:整体区域的右三分之一
region3 = img[overall_y_min:overall_y_max, overall_x_min + 2*split_width:overall_x_max]

# 保存提取的区域(按需启用)
# cv2.imwrite('overall_region.png', overall_region)
# cv2.imwrite('region1.png', region1)
# cv2.imwrite('region2.png', region2)
# cv2.imwrite('region3.png', region3)

# 显示提取结果(按需启用)
cv2.imshow('Overall Region', overall_region)
cv2.imshow('Region 1', region1)
cv2.imshow('Region 2', region2)
cv2.imshow('Region 3', region3)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果说明

  • 整体提取区域:覆盖两位数字上下高度范围的横向长条区域,位于两个数字之间
  • 区域1:整体区域的左三分之一部分
  • 区域2:整体区域的中间三分之一部分
  • 区域3:整体区域的右三分之一部分

如果你的图片尺寸、数字大小有变化,可以调整代码里的轮廓面积阈值(500),或者细分区域的拆分比例,适配你的实际需求~

内容的提问来源于stack exchange,提问作者Kaushik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:44:41