如何用Python根据标注字母分割医学图像为子区域?
基于医学图像标注字母的子区域分割方案
问题背景
需要将带有字母标注的医学图像,按每个标注字母对应的子区域进行分割,现有固定尺寸切片代码无法满足需求。
核心思路
实现这类分割的关键是先定位每个标注字母的位置,再匹配其所属区域的边界,最后完成裁剪,分为三个核心步骤:
- 文字检测:识别图像中的标注字母及坐标
- 区域定位:根据字母位置结合图像线条,确定对应医学区域的边界
- 图像裁剪:按边界分割图像并保存子区域
具体实现步骤与代码
1. 依赖安装
先安装所需工具库:
pip install pillow pytesseract opencv-python
注:Tesseract OCR引擎需单独安装:
- Windows:从官方GitHub仓库下载安装包
- Linux:执行
sudo apt install tesseract-ocr - Mac:执行
brew install tesseract
2. 完整代码示例
import os import cv2 import pytesseract from PIL import Image # Windows系统需指定Tesseract路径,Mac/Linux可注释此行 # pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def split_by_annotation(img_path, output_dir): # 读取图像并预处理,增强文字与线条辨识度 img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 二值化处理,突出前景(文字、线条) _, thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV) # OCR识别文字及对应坐标 ocr_result = pytesseract.image_to_data(thresh, output_type=pytesseract.Output.DICT) box_count = len(ocr_result['text']) # 创建输出目录 os.makedirs(output_dir, exist_ok=True) base_name, ext = os.path.splitext(os.path.basename(img_path)) # 遍历识别结果,筛选单个大写字母的标注 for idx in range(box_count): text = ocr_result['text'][idx].strip() if len(text) == 1 and text.isupper(): # 获取字母的 bounding box 坐标 x, y, w, h = ocr_result['left'][idx], ocr_result['top'][idx], ocr_result['width'][idx], ocr_result['height'][idx] # 确定区域边界(示例逻辑:字母在区域左上角,向右向下扫描找线条边界) # 可根据你的图像实际结构调整边界检测逻辑 region_x1 = x region_y1 = y + h # 从字母下方开始作为区域顶部 # 寻找右侧边界:扫描垂直方向的线条 region_x2 = img.shape[1] for col in range(x + w, img.shape[1]): if cv2.countNonZero(thresh[:, col]) > 10: region_x2 = col break # 寻找下方边界:扫描水平方向的线条 region_y2 = img.shape[0] for row in range(y + h, img.shape[0]): if cv2.countNonZero(thresh[row, :]) > 10: region_y2 = row break # 裁剪并保存子区域 sub_region = img[region_y1:region_y2, region_x1:region_x2] save_path = os.path.join(output_dir, f"{base_name}_region_{text}{ext}") cv2.imwrite(save_path, sub_region) print(f"已保存子区域:{save_path}") # 调用示例 input_img = "/content/drive/MyDrive/Images/image 2.jpg" output_folder = "/content/drive/MyDrive/output_segments" split_by_annotation(input_img, output_folder)
优化建议
- 预处理优化:若图像对比度不足,可添加直方图均衡化(
cv2.equalizeHist(gray))或形态学膨胀操作,强化文字与线条。 - 边界检测优化:使用霍夫变换(
cv2.HoughLinesP)检测图像中的直线,能更精准地定位区域边界,适合结构规整的医学图像。 - OCR精度优化:通过Tesseract参数限制识别字符集,比如添加
config='--psm 10 --oem 3 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ',提升标注字母的识别准确率。
内容的提问来源于stack exchange,提问作者Eda
相关产品推荐
相关产品推荐

