搬来的啊 感谢 ~~ 只为自己学习而已 谅解哈

样例的图不太美观~~~ 别瞎想哦~~

下面是测试图片,目标是提取其中的物体轮廓:

CVの低对比度目标提取_高斯滤波

实现效果如下: 

CVの低对比度目标提取_灰度图_02

实现步骤 

CVの低对比度目标提取_高斯滤波_03

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

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

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

CVの低对比度目标提取_灰度图_04

【2】Canny边缘检测

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

CVの低对比度目标提取_人工智能_05

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

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

CVの低对比度目标提取_灰度图_06

【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)

CVの低对比度目标提取_人工智能_07

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

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

CVの低对比度目标提取_高斯滤波_08

【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)

CVの低对比度目标提取_灰度图_09

CVの低对比度目标提取_灰度图_10

完整源码:

import numpy as np
import cv2

img = cv2.imread('1.jpg')
cv2.imshow('src', img)

h,w,c = img.shape
img = 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()