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

如何使用OpenCV将图像背景改为白色以适配OCR识别

调整OpenCV代码实现OCR图像背景转白

原始图像

原始图像

当前代码运行结果

当前运行结果

当前代码

image = cv2.imread('./screenshot_2.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
threshold_value = 150
_, image = cv2.threshold(gray, threshold_value, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
largest_contour = max(contours, key=cv2.contourArea)
height, width = image.shape
image = np.ones((height, width), np.uint8) * 255 
cv2.drawContours(image, [largest_contour], -1, 0, -1)

期望效果

期望效果

当前代码仅保留了最大轮廓的黑色填充,丢失了原始图像中的文字细节,无法达到期望的背景转白效果。以下是调整后的代码:

import cv2
import numpy as np

# 读取目标图像
image = cv2.imread('./screenshot_2.png')
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 采用OTSU自动阈值进行二值化反转,适配图像灰度分布
_, binary_inv = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# 创建全白背景图像
white_bg = np.ones_like(gray) * 255
# 将二值图中的文字区域(白色部分)映射到白背景上,转为黑色
white_bg[binary_inv == 255] = 0

# 形态学开运算去除小噪点(可选)
kernel = np.ones((2, 2), np.uint8)
result = cv2.morphologyEx(white_bg, cv2.MORPH_OPEN, kernel)

# 输出结果
cv2.imwrite('processed_image.png', result)
cv2.imshow('Processed Image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

关键调整说明:

  • 替换固定阈值为OTSU自动阈值,无需手动调整数值,能更精准分割文字与背景。
  • 跳过寻找最大轮廓的步骤,直接通过二值图映射保留所有文字细节,避免丢失内容。
  • 可选的形态学开运算,可清除阈值处理产生的微小噪点,让最终图像更干净,更适合OCR识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:07:58