Python OpenCV 去除截图中的所有图片
1 import cv2 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 # 读取图像并转换为灰度图像 6 image = cv2.imread('./a.jpg') 7 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 8 9 # 使用 Canny 边缘检测 10 edges = cv2.Canny(gray, 0, 200) # 调整阈值参数 11 12 # 寻找轮廓 13 contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 14 15 # 过滤出长宽大于150的轮廓 16 filtered_contours = [contour for contour in contours if cv2.boundingRect(contour)[2] > 110 and cv2.boundingRect(contour)[3] > 110] 17 18 # 对轮廓按面积进行排序 19 sorted_contours = sorted(filtered_contours, key=cv2.contourArea, reverse=True)[:10] # 只保留最大的五个轮廓 20 21 # 绘制矩形轮廓 22 for contour in sorted_contours: 23 x, y, w, h = cv2.boundingRect(contour) 24 cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) 25 26 # 创建一个与原始图像相同大小的空白图像 27 mask = np.zeros_like(image) 28 29 # 将轮廓内的区域更改为背景颜色 30 for contour in sorted_contours: 31 x, y, w, h = cv2.boundingRect(contour) 32 cv2.rectangle(mask, (x, y), (x + w, y + h), (255, 255, 255), thickness=cv2.FILLED) 33 34 35 # 将填充区域与原始图像进行叠加 36 result = np.where(mask != 255, image, mask) 37 # result = cv2.bitwise_and(image, cv2.bitwise_not(mask)) 38 # 显示结果 39 plt.imshow(result[:,:,::-1])
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?