OpenCV中修改图像局部背景色及黑色背景图像数据提取求助
黑色背景图像数据提取解决方案
问题:我能够提取白色背景图像中的数据,但无法提取黑色背景图像中的数据。相关图像如下:
以下是我尝试过但无效的代码:
#denoise #For normal image #img = cv2.fastNlMeansDenoisingColored(img, None, 3, 3, 7, 21) #gray #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Morp operation #kernel = np.ones((1, 1), np.uint8) #img = cv2.dilate(img, kernel, iterations=1) #img = cv2.erode(img, kernel, iterations=1)
解决方法
- 反转图像颜色:把黑色背景转成白色背景,直接复用你处理白色背景的成熟逻辑,代码示例:
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_inverted = cv2.bitwise_not(img_gray) - 优化阈值处理:针对反转后的图像做二值化,确保前景(原黑色文字)和背景彻底分离,推荐用自适应阈值应对光照不均:
img_threshold = cv2.adaptiveThreshold(img_inverted, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) - 调整形态学操作:1x1的核没有实际效果,换成2x2或3x3的核,根据图像需求选择腐蚀或膨胀顺序,示例:
kernel = np.ones((2, 2), np.uint8) img_processed = cv2.morphologyEx(img_threshold, cv2.MORPH_CLOSE, kernel) # 先膨胀后腐蚀,填补字符间隙 - 针对性去噪:对灰度反转后的图像应用去噪,用灰度图版本的去噪函数更高效:
img_denoised = cv2.fastNlMeansDenoising(img_inverted, None, 10, 7, 21)
完整示例代码
import cv2 import numpy as np # 读取图像 img = cv2.imread("your_image_path.jpg") # 转为灰度并反转 img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_inverted = cv2.bitwise_not(img_gray) # 去噪 img_denoised = cv2.fastNlMeansDenoising(img_inverted, None, 10, 7, 21) # 自适应阈值 img_threshold = cv2.adaptiveThreshold(img_denoised, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # 形态学处理 kernel = np.ones((2, 2), np.uint8) img_processed = cv2.morphologyEx(img_threshold, cv2.MORPH_CLOSE, kernel) # 后续数据提取(复用你白色背景的提取逻辑) # ...
内容的提问来源于stack exchange,提问作者ZKS
相关产品推荐
相关产品推荐

