如何用Python检测WiFi图标Blob并生成对应掩码图像?
Python检测WiFi图标Blob并生成掩码方案
环境准备
先安装依赖库:
pip install opencv-python numpy
实现步骤与代码
下面是针对WiFi图标实现Blob检测、生成三个目标掩码的完整代码,每一步都有注释:
import cv2 import numpy as np # 1. 加载图像并预处理 img = cv2.imread("wifi_icon.png") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 二值化处理:根据图标颜色调整阈值(这里假设图标是深色、背景浅色) # 如果图标是浅色、背景深色,把最后一个参数改成cv2.THRESH_BINARY_INV _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 2. 检测轮廓(Blob) contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 按轮廓面积从小到大排序:对应基础图标(最小)、小曲线、大曲线(最大) contours_sorted = sorted(contours, key=lambda x: cv2.contourArea(x)) # 3. 生成三个掩码 mask_basic = np.zeros_like(gray) mask_small_curve = np.zeros_like(gray) mask_large_curve = np.zeros_like(gray) # 绘制基础图标掩码(最小的轮廓,比如中心圆点) cv2.drawContours(mask_basic, [contours_sorted[0]], -1, 255, thickness=cv2.FILLED) # 绘制小曲线掩码(中间面积的轮廓) cv2.drawContours(mask_small_curve, [contours_sorted[1]], -1, 255, thickness=cv2.FILLED) # 绘制大曲线掩码(最大面积的轮廓) cv2.drawContours(mask_large_curve, [contours_sorted[2]], -1, 255, thickness=cv2.FILLED) # 4. 保存掩码图像 cv2.imwrite("wifi_basic_mask.png", mask_basic) cv2.imwrite("wifi_small_curve_mask.png", mask_small_curve) cv2.imwrite("wifi_large_curve_mask.png", mask_large_curve) # 可选:显示结果,方便调试 cv2.imshow("Original", img) cv2.imshow("Basic Mask", mask_basic) cv2.imshow("Small Curve Mask", mask_small_curve) cv2.imshow("Large Curve Mask", mask_large_curve) cv2.waitKey(0) cv2.destroyAllWindows()
调试与优化建议
- 阈值调整:如果二值化效果不好,修改
cv2.threshold()的第二个参数(阈值127),也可以用自适应阈值适配复杂背景:binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) - 轮廓筛选:如果有噪点轮廓,增加面积过滤条件,只保留有效轮廓:
valid_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 50] contours_sorted = sorted(valid_contours, key=lambda x: cv2.contourArea(x)) - 形状判断:如果面积排序不准确,可以用轮廓外接矩形的宽高比区分,WiFi曲线的外接矩形会比中心圆点宽很多。
内容的提问来源于stack exchange,提问作者YunSheng Liu
相关产品推荐
相关产品推荐

