总体来说效果并不太理想,没有达到预期效果还是调用接口把。。。,代码如下

import cv2
import numpy as np

# 读取图像
image_path = r'D:\test\1.jpg'
image = cv2.imread(image_path)

# 转为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# cv2.imshow("GaussianBlur", blurred)
# 二值化
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)

## 膨胀 → 腐蚀
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
morph = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel,iterations=4)

cleaned = cv2.bitwise_not(morph)

kernel = np.ones((5,5), np.uint8)
closing = cv2.morphologyEx(cleaned, cv2.MORPH_CLOSE, kernel, iterations=2)
# # # 检测轮廓
# contours, _ = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# # 填充轮廓
# for contour in contours:
#     cv2.drawContours(gray, [contour], -1, (255, 255, 255), thickness=cv2.FILLED)


cv2.imshow("Original", gray)
cv2.imshow("Erased", image)
cv2.imshow("cleaned", cleaned)
cv2.imshow("closing", closing)
cv2.waitKey(0)
cv2.destroyAllWindows()