guide
This article mainly introduces a case of low-contrast target extraction implemented by OpenCV (steps + source code).
background introduction
The example comes from the network, the following is the test picture, the goal is to extract the outline of the object:
The effect is as follows:
Implementation steps
Initially, the contrast between the background and the target is not obvious, and it is difficult to distinguish them. But we can still extract the target outline through the traditional Blob analysis method, the steps are as follows:
[1] Convert to grayscale image + Gaussian filter
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (11, 11), 7)
cv2.imshow('blur', blur)
【2】Canny edge detection
canny = cv2.Canny(blur, 0, 42)
cv2.imshow('canny', canny)
【3】Closing operation (connecting the separated contours)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(7,7))
closing = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel, iterations=2)#闭运算
cv2.imshow('closing', closing)
[4] Find the contour + find the maximum area contour (removing interference), you can get the overall contour
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] Perform an open operation on the result of step [3], and wait to get the ontology part:
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel, iterations=1)#闭运算
cv2.imshow('opening', opening)
[6] Find the contour + find the maximum area contour (removing interference):
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)
Complete source code:
# 公众号:计算机视觉之家
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()