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

如何用OpenCV在图像中绘制三条不覆盖黑色像素的水平线?

需求:在图像空白区域绘制三条不覆盖黑色像素的水平线

输入图像

输入图像

目标效果示例

目标效果示例

我刚接触Python OpenCV,希望无需训练机器学习(ML)或深度学习(DL)模型,在输入图像的任意位置绘制三条水平线,且确保这些线条不会覆盖任何黑色像素,最终效果如示例图所示。

我在网上找到的相关代码多为线条检测或段落检测类,如下所示:

import cv2
from imutils import contours
import imutils

def captch_ex(file_name):
    img = cv2.imread(file_name)

    img_final = cv2.imread(file_name)
    img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, mask = cv2.threshold(img2gray, 180, 255, cv2.THRESH_BINARY)
    image_final = cv2.bitwise_and(img2gray, img2gray, mask=mask)
    ret, new_img = cv2.threshold(image_final, 180, 255, cv2.THRESH_BINARY_INV)  # 针对黑色文本使用cv.THRESH_BINARY_INV
    '''
            第8到12行:去除噪点部分
    '''
    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,
                                                         3))  # 通过调整核的尺寸控制膨胀方向,x值大则水平方向膨胀更多,y值大则垂直方向膨胀更多
    dilated = cv2.dilate(new_img, kernel, iterations=9)  # 膨胀操作,迭代次数越多膨胀效果越明显


    contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # findContours返回轮廓相关的三个变量

for contour in contours:
    # 获取轮廓的外接矩形
    x, y, w, h = cv2.boundingRect(contour)

    # 过滤掉不是文本的小尺寸误检区域
    if w < 35 and h < 35:
        continue

    # 在原始图像上绘制轮廓的外接矩形
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 1)

    '''
    # 可以裁剪图像并送入OCR,误检区域通常不会返回文本内容 :)
    cropped = img_final[y :y +  h , x : x + w]

    s = file_name + '/crop_' + str(index) + '.jpg' 
    cv2.imwrite(s , cropped)
    index = index + 1

    '''
# 显示添加了轮廓的原始图像
cv2.imshow('captcha_result', img)
cv2.waitKey()


file_name = '2.png'
captch_ex(file_name)

恳请各位指导如何实现示例中的效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:40:32