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

如何基于Python OpenCV为已去噪图像中的文本块绘制边界框并修改现有去噪代码实现保存

How to Add Text Block Bounding Boxes to Your Denoised Image

Got it! You can modify your existing remove_dots function to draw bounding boxes around text blocks without disrupting your current noise-removal workflow. The key is to capture valid text contour coordinates while building your mask, then draw the boxes on the final denoised image. Here's the adjusted code and breakdown:

Modified Full Code

import cv2
import matplotlib.pyplot as plt
import glob
import os
import numpy as np

def remove_dots(image_path, outdir):
    image = cv2.imread(image_path)
    mask = np.zeros(image.shape, dtype=np.uint8)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (3,3), 0)
    thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,51,9)
    # Create horizontal kernel then dilate to connect text contours
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    dilate = cv2.dilate(thresh, kernel, iterations=2)
    # Find contours and filter out noise using contour approximation and area filtering
    cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    
    # Store coordinates of valid text blocks
    text_boxes = []
    
    for c in cnts:
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.04 * peri, True)
        x,y,w,h = cv2.boundingRect(c)
        area = w * h
        ar = w / float(h)
        if area > 1200 and area < 50000 and ar <8:
            cv2.drawContours(mask, [c], -1, (255,255,255), -1)
            # Save the bounding box coordinates
            text_boxes.append((x, y, w, h))
    
    # Generate the denoised result image
    mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
    result = cv2.bitwise_and(image, image, mask=mask)
    result[mask==0] = (255,255,255) # Set background to white
    
    # Draw bounding boxes on the denoised image
    for (x, y, w, h) in text_boxes:
        # Customize color (BGR format) and thickness here
        cv2.rectangle(result, (x, y), (x + w, y + h), (0, 0, 255), 2)
    
    # Save the final image with bounding boxes
    cv2.imwrite(os.path.join(outdir, os.path.basename(image_path)), result)

for jpgfile in glob.glob(r'C:\custom\TableDetectionWork\text_detection_dataset/*'):
    print(jpgfile)
    remove_dots(jpgfile,r'C:\custom\TableDetectionWork\textdetect/')

What Changed?

  • Added a text_boxes list: We collect the (x, y, w, h) coordinates of every contour that meets your text block criteria (area and aspect ratio) while we're building the noise mask. This avoids redundant contour loops.
  • Drew boxes on the final result: After generating your denoised result image, we loop through the stored coordinates and use cv2.rectangle() to draw visible boxes. The red color ((0,0,255) in OpenCV's BGR format) and thickness (2 pixels) can be adjusted to match your needs.
  • No disruption to existing logic: Your original noise-removal steps stay intact—we just added the box-drawing step after generating the clean image.

内容的提问来源于stack exchange,提问作者Hamad Yunis 2330-FETBSEEF14

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:22:38