实战 | OpenCV实现的低对比度目标提取(步骤 + 源码)

导  读

    本文主要介绍一个OpenCV实现的低对比度目标提取的案例(步骤 + 源码)。

背景介绍

    实例来源于网络,下面是测试图片,目标是提取其中的物体轮廓:

图片

    实现效果如下:   

图片

实现步骤

图片

    初步来看背景与目标对比度不明显,不易区分。但我们还是可以通过传统Blob分析方法提取目标轮廓,步骤如下:

【1】转为灰度图 + 高斯滤波

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)blur = cv2.GaussianBlur(gray, (11, 11), 7)cv2.imshow('blur', blur)

图片

【2】Canny边缘检测​​​​​​​

canny = cv2.Canny(blur, 0, 42)cv2.imshow('canny', canny)

图片

【3】闭运算(将分离轮廓连接)​​​​​​​

kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(7,7))closing = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel, iterations=2)#闭运算cv2.imshow('closing', closing)

图片

【4】查找轮廓 + 求最大面积轮廓(剔除干扰),即可获取整体轮廓​​​​​​​

contours, hierarchies = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)cnt = max(contours, key=cv2.contourArea)cv2.drawContours(img, cnt, -1, (0, 0, 255), 2)

图片

【5】对第【3】步结果做开运算,等得到本体部分:​​​​​​​

opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel, iterations=1)#闭运算cv2.imshow('opening', opening)

图片

【6】查找轮廓 + 求最大面积轮廓(剔除干扰):​​​​​​​

contours, hierarchies = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)cnt = max(contours, key=cv2.contourArea)cv2.drawContours(img, cnt, -1, (0, 255, 0), 2)

图片

图片

完整源码:

# 公众号:计算机视觉之家import numpy as npimport cv2
img = cv2.imread('1.jpg')cv2.imshow('src', img)
h,w,c = img.shapeimg = cv2.resize(img, (w // 2, h // 2))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)blur = cv2.GaussianBlur(gray, (11, 11), 7)cv2.imshow('blur', blur)canny = cv2.Canny(blur, 0, 42)cv2.imshow('canny', canny)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(7,7))closing = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel, iterations=2)#闭运算cv2.imshow('closing', closing)
##contours, hierarchies = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)##cnt = max(contours, key=cv2.contourArea)##cv2.drawContours(img, cnt, -1, (0, 0, 255), 2)
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel, iterations=1)#闭运算cv2.imshow('opening', opening)
contours, hierarchies = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)cnt = max(contours, key=cv2.contourArea)cv2.drawContours(img, cnt, -1, (0, 255, 0), 2)
cv2.imshow('result', img)cv2.waitKey(0)cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/stq054188/article/details/132257078