以下解决方案使用 OpenCV 和 Numpy 库,但产生的结果比 Paint.Net 还要好。代码部分的解释是内联的:
import numpy as np
import cv2
# The standard stuff: image reading, grayscale conversion, inverting, morphology & edge detection
image = cv2.imread('charm.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.bitwise_not(gray)
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, sqKernel)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
edges = cv2.Canny(thresh, 50, 200)
# Finding and sorting contours based on contour area
cnts = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
# Filling the contours with black color
for c in cnts:
cv2.drawContours(image, [c], -1, (0, 0, 0), -1)
# Displaying the result
cv2.imshow("Contour", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出结果: