Führung
In diesem Artikel wird hauptsächlich ein Fall der von OpenCV implementierten Zielextraktion mit geringem Kontrast vorgestellt (Schritte + Quellcode).
Hintergrundeinführung
Das Beispiel stammt aus dem Netzwerk, das Folgende ist das Testbild, das Ziel besteht darin, den Umriss des Objekts zu extrahieren:
Der Effekt ist wie folgt:
Umsetzungsschritte
Zunächst ist der Kontrast zwischen Hintergrund und Ziel nicht offensichtlich und es ist schwierig, sie zu unterscheiden. Wir können die Zielkontur jedoch immer noch mit der herkömmlichen Blob-Analysemethode extrahieren. Die Schritte sind wie folgt:
[1] In Graustufenbild + Gauß-Filter konvertieren
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (11, 11), 7)
cv2.imshow('blur', blur)
【2】Gekonnte Kantenerkennung
canny = cv2.Canny(blur, 0, 42)
cv2.imshow('canny', canny)
【3】Schließvorgang (Verbinden der getrennten Konturen)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(7,7))
closing = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel, iterations=2)#闭运算
cv2.imshow('closing', closing)
[4] Finden Sie die Kontur + finden Sie die maximale Flächenkontur (Entfernen von Interferenzen). Sie können die Gesamtkontur erhalten
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] Führen Sie eine Öffnungsoperation für das Ergebnis von Schritt [3] durch und warten Sie, bis Sie den Ontologieteil erhalten:
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel, iterations=1)#闭运算
cv2.imshow('opening', opening)
[6] Finden Sie die Kontur + finden Sie die Kontur mit der maximalen Fläche (Entfernen von Interferenzen):
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)
Vollständiger Quellcode:
# 公众号:计算机视觉之家
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()