利用python-opencv找出成块的黑色背景噪声(使用场景:例如SIFT算法把图透视变化以后,可能会出现成块的黑色噪声,后续其他操作可能需要判断某些点的有效性,有效的定义是不在黑色块中)

该代码示例展示了如何利用OpenCV库进行图像处理,包括将BGR图像转换为HSV,检测黑色区域,进行轮廓检测,并通过pointPolygonTest判断一个点是否位于这些轮廓内。文章还提到了自定义阈值以过滤掉小的轮廓,并提供了处理前后图像的保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码:

import cv2
import numpy as np
def isPointInBlackContours(point, frame, maskBlackImgPath, maskImgPath):
    ######步骤1:提取出黑色区域置为白亮,其他区域置为黑色背景化:
    # 把 BGR 转为 HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    # HSV中黑色范围
    lower_blue = np.array([0, 0, 0])
    upper_blue = np.array([0, 0, 0])
    # 获得黑色区域的mask
    mask = cv2.inRange(hsv, lower_blue, upper_blue)
    # 和原始图片进行and操作,获得黑色区域。黑色区域置为白亮,其他区域置为黑色背景化。
    res = cv2.bitwise_and(frame, frame, mask=mask)
    cv2.imwrite(maskBlackImgPath, mask)

    ######步骤2:轮廓检测并且绘制保存在本地
    # 读入图像、灰度、二值化
    img_src = cv2.imread(maskBlackImgPath)
    img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
    val, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
    # 查找轮廓
    contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    print('len(contours):', len(contours))
    # 绘制轮廓
    validContoursList = []
    for ind in range(len(contours)):
        # perimeter = cv2.arcLength(contours[ind], True)
        contourArea=cv2.contourArea(contours[ind], False)
        if (contourArea>500):#自定义阈值,抑制过小的误检轮廓或者黑颜色物体
            print("contourArea:"+str(contourArea))
            print("Valid Contour index:" + str(ind))
            cv2.drawContours(img_src, contours, ind, (0, 0, 255), 3)
            validContoursList.append(contours[ind])
    cv2.imwrite(maskImgPath, img_src)

    ####步骤3:判断一个点是否在轮廓内
    # img = cv2.imread(maskImgPath)
    # img = cv2.circle(img, point, 2, (255, 0, 0), 2)  # 蓝色
    for indexJ in range(len(validContoursList)):
        dstJ = cv2.pointPolygonTest(validContoursList[indexJ], point, 1)
        print("dst"+str(indexJ)+':'+str(dstJ))
        if(dstJ>=0):   #距离>=0,说明在黑色轮廓以及内部
            return True
    return False


pt = (131, 104)
frame = cv2.imread('d:/11.jpg')
maskBlackImgPath1='d:/mask1.jpg'
maskImgPath1='d:/validContours2.jpg'
res1=isPointInBlackContours(pt,frame,maskBlackImgPath1,maskImgPath1)
print('res:'+str(res1))

原图11.jpg :

 结果图 mask1.jpg   (原黑色块高亮显示):

结果图  validContours2.jpg (用红色框,自动标记出原黑色噪声块):

 参考①:

OpenCV-Python教程:查找轮廓、绘制轮廓_python获取轮廓上两点之间的所有点_桔子code的博客-CSDN博客

参考②:

opencv 判断点在多边形内外_cv2.pointpolygontest_alex1801的博客-CSDN博客

参考③:

Python进行SIFT图像对准 - 简书

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值