犯罪嫌疑人X
希望我没有把问题简单化,但从我的角度来看,使用 OpenCV 和简单的阈值、形态学操作,findContours应该可以完成这项工作。请看下面的代码:import cv2import numpy as np# Inputinput = cv2.imread('images/x0ziO.png', cv2.IMREAD_COLOR)# Input to grayscalegray = cv2.cvtColor(input, cv2.COLOR_BGR2GRAY)# Binary threshold_, gray = cv2.threshold(gray, 20, 255, cv2.THRESH_BINARY)# Morphological improvements of the maskgray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)))# Find contourscnts, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)# Filter large size contours; at the end, there should only be one leftlargeCnts = []for cnt in cnts: if (cv2.contourArea(cnt) > 10000): largeCnts.append(cnt)# Draw (filled) contour(s)gray = np.uint8(np.zeros(gray.shape))gray = cv2.drawContours(gray, largeCnts, -1, 255, cv2.FILLED)# Calculate background pixel areabgArea = input.shape[0] * input.shape[1] - cv2.countNonZero(gray)# Put result on input imageinput = cv2.putText(input, 'Background area: ' + str(bgArea), (20, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.0, (255, 255, 255))cv2.imwrite('images/output.png', input)中间的“面具”图像如下所示:并且,最终输出如下所示: